0

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]]
Muddyblack k
  • 314
  • 3
  • 16

2 Answers2

1

Try creating the list with explicit elements

test = list([list([0 for i in range(2)]) for j in range(2)])
Runinho
  • 439
  • 1
  • 6
1

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