Arrays · 9 / 23 Theory

List aliases and copies

Assigning a list to another variable does not copy it: both variables point to the same object, and changing one changes the other. To get an independent list you must copy it explicitly.

a = [1, 2, 3]
b = a              # does NOT copy: b and a are the SAME list
b.append(4)
print(a)           # [1, 2, 3, 4]

c = a[:]           # shallow copy with slicing
d = list(a)        # another way
e = a.copy()       # and another
c.append(5)
print(a, c)        # [1, 2, 3, 4] [1, 2, 3, 4, 5]

m = [[0, 0], [0, 0]]
t = m[:]                   # shallow copy: the rows are shared
t[0][0] = 9
print(m)                   # [[9, 0], [0, 0]]

f = [[0] * 2] * 2          # careful! both rows are the same list
f[0][0] = 7
print(f)                   # [[7, 0], [7, 0]]

g = [[0] * 2 for _ in range(2)]   # this way each row is independent
g[0][0] = 7
print(g)                   # [[7, 0], [0, 0]]
  • b = a creates an alias, not a copy.
  • a[:], list(a) and a.copy() make a shallow copy: the list is new, but the elements are the same objects. With lists inside lists, the rows are shared.
  • [[0] * n] * m repeats the same row m times; use a comprehension to create distinct rows.
  • To copy the nested elements too you use copy.deepcopy (you will see it in the article about mutability in Data types).

An alias is useful when you want a function to modify the list it receives; if you do not want that, work on a copy. Practice with Remove duplicates keeping the order, which builds a new list without touching the original.