[0] * size_of_array
creates a list which multiple references to 0
. If you put another value into this list, it won't be affected.
As you noticed, [[]] * num
creates a list which contains a reference to the same list over and over again. Of you change this list, the change is visible via all references.
>>> a = [0] * 10
>>> [id(i) for i in a]
[31351584L, 31351584L, 31351584L, 31351584L, 31351584L, 31351584L, 31351584L, 31351584L, 31351584L, 31351584L]
>>>
>>> all(i is a[0] for i in a)
True
vs.
>>> a = [[]] * 10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> [id(i) for i in a]
[44072200L, 44072200L, 44072200L, 44072200L, 44072200L, 44072200L, 44072200L, 44072200L, 44072200L, 44072200L]
>>> all(i is a[0] for i in a)
True
Same situation, but one thing is different:
If you do a[0].append(10)
, the effect is visible in all lists.
But if you do a.append([])
, you add a clean, new list which isn't related to the others:
>>> a = [[]] * 10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a.append([])
>>> a[0].append(8)
>>> a
[[8], [8], [8], [8], [8], [8], [8], [8], [8], [8], []]
>>> a[-1].append(5)
>>> a
[[8], [8], [8], [8], [8], [8], [8], [8], [8], [8], [5]]