0

A simple piece of logic I wanted to write was to generate a 5x5 grid of all -1's filled in initially and then change the first value in the top left corner indexed 0,0 to 1. How and why does the internal python logic interpret the underlying grid lists as the same exact grid and was this always the case?

grid = [[-1] * 5] * 5
grid[0][0] = 1
print(grid)

Returns: [[1, -2, -2, -2, -2], [1, -2, -2, -2, -2], [1, -2, -2, -2, -2], [1, -2, -2, -2, -2], [1, -2, -2, -2, -2]]

I mean I can create a dictionary to deal with this or get around it like such:

[[-1 for x in range(column_count)] for y in range(row_count)] 
# or 
[[-1] * column_count for y in range(row_count)] 

But I am just confused as to why the shorter form does not work and what logic or usage that it has. Is this just one of the python puzzlers, basically never use the style for anything but 1D numbers?

grid = [test.copy()] * 5
grid2 = [test.copy() for y in range(5)] 
grid2[0][0] = 10
grid[0][0] = 10
print(grid)
print(grid2)

Returns:

[[10, 2, 3, 4, 5], [10, 2, 3, 4, 5], [10, 2, 3, 4, 5], [10, 2, 3, 4, 5], [10, 2, 3, 4, 5]]
[[10, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

0 Answers0