Skip to content

Mutability, aliasing, and copying [ref]

Problem

  • Alias a = [1, 2] as b, then append 3 through b.
  • Shallow-copy [1, 2], then append 3 only to the copy.
  • Replace the contents of a = [1, 2] while retaining an alias to its list object.
  • Shallow-copy [[1], [2]], then mutate its first inner list.
  • Create three independent empty inner lists.

Python solution

a = [1, 2]
b = a
b.append(3)
(a, b, a is b)  # ([1, 2, 3], [1, 2, 3], True)

a = [1, 2]
b = a[:]
b.append(3)
(a, b, a is b)  # ([1, 2], [1, 2, 3], False)

a = [1, 2]
alias = a
a[:] = [8, 9]
(alias, alias is a)  # ([8, 9], True)

a = [[1], [2]]
b = a[:]
b[0].append(9)
(a, b)  # ([[1, 9], [2]], [[1, 9], [2]])

rows = [[] for _ in range(3)]
rows[0].append(1)
rows  # [[1], [], []]