When you use the *
operator to repeat a list in Python, it simply creates repeated references to the original list, as opposed to creating multiple independent lists. You can use Python's id
function to find the internal identification number for any Python value, which can be used to tell if two similar values are actually distinct or not. For example:
>>> t = [[9]*3]*3
>>> t
[[9, 9, 9], [9, 9, 9], [9, 9, 9]]
>>> id(t[0])
4354326848
>>> id(t[1])
4354326848
>>> id(t[2])
4354326848
>>> t = [[-9, -9, -9], [-9, -9, -9], [-9, -9, -9]]
>>> id(t[0])
4354326912
>>> id(t[1])
4354327616
>>> id(t[2])
4354327168
Observe than in the first case, all three of the id numbers are the same, while in the second case, they are all different.
So, in the first case, you really had three references to the same underlying list, and when you changed an element of one of them, they all changed together (since they were really all one list).