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

51 views Asked by At

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:

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

There are 2 answers

0
Lorenzo Cacciola On BEST ANSWER

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

0
Runinho On

Try creating the list with explicit elements

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