Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – not exactly predefined 2D Array overwrites just all elements

Hey I want to create a 2d-Array with no predefined length and then replace the elements. without using numpy.

Here a simplified version with my Problem:

>>> test = 2*[2*[0]]
>>> test[0][0] = "Hello"
>>> print(test)
[['Hello', 0], ['Hello', 0]]

This is the output I would like to have:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['Hello', 0], [0, 0]]

>Solution :

This is because you are creating a copy of the address of the memory, to create a 2d Array you have to use a list comprehension

test = [[0 for i in range(2)] for j in range(2)]

try use this

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading