Reputation: 29
I have this code that doesn't work the way I expect it to. I'm trying to make a grid. It should output the tuple from the list, but it's stuck on the first number.
Is there a problem with my logic?
row = []
grid = []
for y in range(0,3):
row.append((0,0))
for x in range(0,3):
grid.append(row)
for y in range(0, 3):
for x in range (0, 3):
print (x,y)
grid[x][y] = (x,y)
print (grid[x][y])
print ("\nTesting:")
for y in range(0, 3):
for x in range (0, 3):
print (grid[x][y])
What it outputs is this:
0 0
(0, 0)
1 0
(1, 0)
2 0
(2, 0)
0 1
(0, 1)
1 1
(1, 1)
2 1
(2, 1)
0 2
(0, 2)
1 2
(1, 2)
2 2
(2, 2)
Testing:
(2, 0)
(2, 0)
(2, 0)
(2, 1)
(2, 1)
(2, 1)
(2, 2)
(2, 2)
(2, 2)
Upvotes: 1
Views: 52
Reputation: 71570
It's because tuples are hashable, so you would have to copy those objects:
for x in range(0, 3):
grid.append(row.copy())
Upvotes: 0
Reputation: 24691
The problem is this:
for x in range(0,3):
grid.append(row)
Keep in mind that row
is the name that refers to a particular list. By executing this line of code multiple times, you're adding the same list to grid
multiple times. In other words, grid[0]
, grid[1]
, and grid[2]
are all pointing to the same piece of memory.
As such, when you modify the list that all three are pointing at, then all three will display the changes.
To avoid this you need to make a copy of the list when inserting it, so you're not inserting the same object multiple times (just copies of the same object). The easiest way to do this is to make a blank slice:
for x in range(0, 3):
grid.append(row[:])
Upvotes: 3