Why b = a is not a copy, traced through id() โ and the slicing trick that actually clones a list.
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.
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.b = a does not create a copy โ it creates an alias. Both names point to the exact same object.a[:]) on a list creates a new object โ a real, independent copy (this is a shallow copy).>>> 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!
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
>>> 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
b = a โ aliasing: same object, two names, mutations through either name are visible via both.b = a[:] (slicing the whole list) โ shallow copy / cloning: a genuinely new list object; changes to b don't affect a, and vice versa.[:] (this deeper case โ shallow vs. deep copy for nested structures โ wasn't shown in these screenshots and should be verified against your video before adding to the note).b = a โ alias, NOT a copy. Same id(). Mutating one affects the other.b = a[:] โ clone, a genuine copy. Different id(). Mutating one does NOT affect the other.[:]) is the quick, common way to shallow-copy a list; list.copy() does the same thing.copy.deepcopy()) is a separate, deeper topic not covered by these particular screenshots.