I came across a piece of python list decclaration. I am bit confused about the behavior of it.
Can somone please explain this. Appreciate your help.
>>> v = [[0]*2]*2
>>> v
[[0, 0], [0, 0]]
>>> v[1][1] = 23
>>> v
[[0, 23], [0, 23]]
>>> v[1][1] = 44
>>> v
[[0, 44], [0, 44]]
>>>
The
*operator for lists repeats their contents, as you can clearly see in the output.However, it does not copy elements, it just copies object references. So in this case, both
[0,0 ]s have the same underlying list object, which should explain the phenomenon.To verify this, try
v[0] = [0,44]to assign a new (and thus independent!) list object to the first element of the master list; then re-try changingv[1][1]. This time only one entry will change in the output.