Concept
Copying Lists: The Reference Trap
Typing `b = a` doesn't copy the list. It creates a second alias pointing to the identical memory address. Use `a.copy()` or `a[:]` for a real duplicate.
python
a = [1, 2]
b = a # Alias! Modifying b modifies a!
c = a.copy() # Real independent clone
b.append(3)
print(a) # [1, 2, 3]
print(c) # [1, 2]
# 73. Copying Lists: The Reference Trap Typing `b = a` does NOT copy the list. It creates a second variable pointing to the exact same list in RAM: ```python a = [1, 2] b = a # Alias! Modifying b modifies a! c = a.copy() # Real independent clone b.append(3) print(a) # [1, 2, 3] print(c) # [1, 2] ``` To create an independent clone so modifications to one don't destroy the other, use `a.copy()` or the slice shorthand `a[:]`.
Checkpoint
If `x = [1, 2]` and `y = x`, what happens to `x` when you run `y.append(3)`?
Practice
Make a true independent copy of `original = [10, 20]` using `.copy()` into variable `backup`. Append `30` to `original`, and print `backup`.
01
Tap code blocks below to assemble
Available Blocks