Shallow Copy vs Aliasing (copy vs [:])

Why b = a is not a copy, traced through id() โ€” and the slicing trick that actually clones a list.

Overview

This topic covers the classic aliasing bug that happens when you assign one variable to another with mutable objects like lists โ€” and the fix using slicing ([:]) to create an independent copy.

โš ๏ธ Note: The screenshots for this session demonstrate aliasing and the shallow-copy fix via slicing (L[:]). They do not show copy.deepcopy() or a case with nested mutable objects being deep-copied โ€” if your course also covers deep copy with copy.deepcopy(), that will need to be added from a separate set of screenshots so nothing here is invented.

Key Concepts

Detailed Explanation

1. The Aliasing Pitfall

>>> a = [1, 2, 3]
>>> b = a          # b is an ALIAS of a โ€” NOT a copy
>>> b.append(4)
>>> print(a)
[1, 2, 3, 4]       # a also changed! Because a and b point to the SAME object

Diagram:

a โ”€โ”€โ”
    โ”œโ”€โ”€โ–บ [0x1000 | [1, 2, 3, 4] ]
b โ”€โ”€โ”˜

Confirmed with id():

>>> L = [1, 2, 3]
>>> L1 = L          # aliasing (NOT a copy)
>>> id(L) == id(L1)
True
>>> L1.append(5)
>>> L1
[1, 2, 3, 5]
>>> L
[1, 2, 3, 5]        # L also changed โ€” same underlying object!
โš ๏ธ Common bug source: b = a never copies a mutable object. Both names refer to the exact same object โ€” mutating through one name affects the other, which is rarely what a beginner intends.

Aliasing also happens naturally with chained assignment:

>>> a = "Hello"
>>> b = a
>>> c = b
>>> id(a), id(b), id(c)
# all three point to the SAME address

2. The Fix: Cloning with Slicing ([:])

>>> L = [1, 2, 3, 4]
>>> L1 = L[:]        # slicing creates a NEW list โ€” a real copy/clone
>>> id(L) == id(L1)
False
>>> L1.append(5)
>>> L1
[1, 2, 3, 4, 5]
>>> L
[1, 2, 3, 4]         # L is unaffected โ€” L1 is a completely separate object

This technique โ€” using [:] to produce an independent copy โ€” is referred to as Cloning.

Diagram:

L  โ”€โ”€โ–บ [0x1000 | [1,2,3,4] ]

L1 = L[:]

L1 โ”€โ”€โ–บ [0x2000 | [1,2,3,4] ]   โ† separate object, same values

Important Points

Quick Revision