The *
operator essentially takes the old list, and recreates it n
times. The new items are the same (the same references) as the old ones, but the list if n
times as long.
The original list is not modified, where simply appending new copies to the end would modify it.
Eg:
[1,2,3] * 3 = [1,2,3,1,2,3,1,2,3]
[[1],[2]] * 3 = [[1],[2],[1],[2],[1],[2]]
>>> myfunc = lambda: None
>>> a = [myfunc]
>>> a
[<function <lambda> at 0x03193468>]
>>> b = a * 2
>>> b
[<function <lambda> at 0x03193468>, <function <lambda> at 0x03193468>]
>>> a
[<function <lambda> at 0x03193468>]
>>> b is a
False
>>> a is b
False
Achieving the 'same' thing with append
:
>>> X = [1,2]
>>> a = X.copy()
>>> n = 2
>>> b = a
>>> for i in range(n-1):
for j in X:
b.append(j)
>>> b
[1,2,1,2]
>>> a
[1,2,1,2]
>>> X
[1,2]
>>> a is b
True
>>> b is a
True