I want to create a 2D array, like so:
grid[y][x]
So that there are y amount of rows and x amount of columns.
Below is the way I did it, but I when I tried to assign the (0,0) of the array to contain the value ‘2’, the code assigned the first value of each subarray to ‘2’.
Why is this happening? How should I pythonically instantiate a 2D array?
n = 4
x=0
y=0
grid = [[None]*n]*n
print grid
grid[y][x]='Here'
print grid
when you use
*you create multiple references, it does not copy the dataso when you modify the first line to
you actually change all lines.
solution
Edit (from other post) Since only the lists are mutable (can change in place) you can also do
Each of the rows are then still unique. If the
Noneobject could be changed in place this would not work.