Course outline · 0% complete

0/32 lessons0%

Course overview →

Two Names, One List

lesson 6-4 · ~9 min · 20/32

Assignment copies the name, not the list

b = a does NOT copy a list. This follows from what assignment has meant since lesson 1-2: it attaches a name to a value, it never duplicates the value. After b = a, both names point to the same list in memory, so a change made through either name is visible through both.

You never noticed this with ints and strings because they are immutable, there is nothing a second name could change. Lists are mutable, so a shared list can be edited out from under you, and that is a classic real-world bug: a second variable, or a function you passed the list to, "mysteriously" modifies your data.

When you genuinely want an independent copy, build one: list(a) (or the slice a[:]) creates a new list containing the same items.

ab[1, 2, 3, 4]b = a : one list, two namesc[1, 2, 3, 99]c = list(a) : a new listassignment shares, list() copies
b = a points a second name at the same list. list(a) builds a genuinely separate list that can change independently.

Code exercise · python

Predict all three printed lists before running. b shares a's list, so the append through b shows up in a. c is a real copy, so its append leaves a alone.

Quiz

What does this print? ```python x = [1, 2] y = x y.append(3) print(x) ```

Code exercise · python

Your turn. Take a real backup of `original` with list() BEFORE appending `gym` to the original, then print the original and the backup. If your backup also shows gym, you copied the name instead of the list.