pythonmultidimensional-arraypredefined-variables

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:

[['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