I have been using the [Value] * Count
notation in Python for initializing a list. For eg., [False] * 3
results in creation of list [False, False False]
. I tried using the same notation for initializing a list of lists.
>>>a = [[0] * 2] * 3
>>>print a
[[0, 0], [0, 0], [0, 0]]
>>>a[0][1] = 23
>>>print a
[[0, 23], [0, 23], [0, 23]]
>>>id(a[0])
139978350226680
>>>id(a[1])
139978350226680
>>>id(a[2])
139978350226680
As we can see, the elements of a refer to a single list thrice instead of referring to three different lists. 1. Why does this happen? 2. What is the correct way to initialize a list of lists?
The same behavior has been pointed out in an answer previously: https://stackoverflow.com/a/13382804/4716199