I was looking at initialising a 2D list in python using grid = [['x']*4]*6
essentially to create a 2D list with six rows with four x's. So, I hoped it would be the same as this approach:
grid2 = [['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x']]
To check they are the same, I used print(grid == grid2)
, which python reports as True.
Next, I would like to assign grid[0][0] ='O'
, to change the first 'x' to 'O', but I have a different outcome based on whether I initialised using the method used for grid and grid2. The grid = [['x']*4]*6
method changes the first element of each list in the 2D array, while the longer initialisation method does what I want, it changes just the x at row & column = 0. I do not understand why it is not the same? I am sure there is someone out there who can explain this to me because I am mystified by this, it might be obvious, but I cannot spot it. My test code is below:
Thanks!
#change identifier names between grid and grid2 to test. i.e change grid to grid2, vice versa. See the difference in behaviour?
grid2 = [['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x']]
grid = [['x']*4]*6
print(grid == grid2)
print(grid)
print(grid2)
print()
for r in grid:
for c in r:
print(c, end = " ")
print()
grid[0][0] ='O' # This behaves differently depending on whether I use grid or grid2
print()
for r in grid:
for c in r:
print(c, end = " ")
print()