Let's say I have the following code:
a_list = [[0]*10]*10
This generates the following list:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Then I want to modify the first element in the first list:
a_list[0][0] = 23
I expected only the first element of the list to be modified, but actually the first element of each list was changed:
[[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[23, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
I managed to find another way to represent my data to avoid this but why is this happening? Why isn't just the first list changed? When I do the second *10
, does Python actually copy the first list's address instead of allocating a new memory block?