operator* multiplies the same reference


In [1]:
l = [[]] * 3
l[0] is l[1], l[0] is l[2]


Out[1]:
(True, True)

In [2]:
l[0].append("abc")
l


Out[2]:
[['abc'], ['abc'], ['abc']]

In [3]:
l = [1] * 3
print(l)
l[0] is l[1], l[0] is l[2]


[1, 1, 1]
Out[3]:
(True, True)

Changing l[1] actually references a different object

Integers are immutable.


In [4]:
l[1] = 2
print(l)
l[0] is l[1], l[0] is l[2], l[1] is l[2]


[1, 2, 1]
Out[4]:
(False, True, False)

Setting l[2] to the same number does not create a new object


In [5]:
l[2] = 2
print(l)
l[0] is l[1], l[0] is l[2], l[1] is l[2]


[1, 2, 2]
Out[5]:
(False, False, True)

Common integers are preallocated


In [6]:
for i in range(-10, 260):
    x = i
    y = i + 1 - 1
    if x is not y:
        print(i)


-10
-9
-8
-7
-6
257
258
259

List comprehensions are one way to create separate lists


In [7]:
l = [[] for _ in range(3)]
l


Out[7]:
[[], [], []]

In [8]:
l[0].append("abc")
l


Out[8]:
[['abc'], [], []]