Two Names, One List

Assigning a list to a second name does not copy it. Watch two names share one list, then see how copy() makes a separate one.

Python · beginner · 8 min · 8 steps · free

What you'll learn

aliasing.py

a = [1, 2, 3]
b = a
b.append(4)
print(a)

c = a.copy()
c.append(5)
print(a)
print(c)

Step by step

  1. Python builds a list object holding 1, 2 and 3, then makes the name a point to it. The name and the list are two separate things.
  2. b = a does not copy the list. It makes a second name, b, point to the very same list object. There is still only one list.
  3. b.append(4) adds 4 to the list that b points to. Because a points to that same list, a sees the change too.
  4. Printing a shows four items, even though the code never called a.append. Both names lead to the one list that was changed.
  5. a.copy() builds a brand new list with the same items, and c points to that new list. Now there are two list objects.
  6. c.append(5) changes only the new list. The original list that a and b share is left alone.
  7. a still has four items. Appending to the copy did not touch it.
  8. c has five items. Use copy() whenever you want a list you can change without affecting the original.

Common mistakes

Best practices

Key takeaways

Check yourself

After x = [1], y = x and y.append(2), what is x?

Answer: [1, 2]. x and y are two names for one list, so the append shows through both.

Which line gives you an independent list?

Answer: b = a.copy(). copy() builds a new list; plain assignment only adds a name.

·

More in Collections