How it works
A Python variable is a name bound to an object, and the type belongs to the object rather than to the name. Rebinding a name to a different type is legal.
Track what each name currently refers to, especially after reassignment inside a branch.
Common error
Assuming a name keeps its original type. Nothing prevents it changing, and the error surfaces far from the cause.
Worked example
Python
value = 7
print(type(value).__name__)
value = "seven"
print(type(value).__name__)Output
int
strA name refers to an object; assignment can later bind the name to a different object type. This does not convert the original object in place.
Exercises
1.1.1 · Trace
Determine the exact output and explain the state changes.
Python
a = [1, 2]
b = a
b.append(3)
print(a)Show solution
Output
[1, 2, 3]Both names refer to the same mutable list.
1.1.2 · Write code
Make an independent copy of [1, 2], append 3 only to the copy, and print both.
Show solution
A shallow copy is enough for this list of immutable integers.
One valid solution
a = [1, 2]
b = a.copy()
b.append(3)
print(a)
print(b)Expected output
[1, 2]
[1, 2, 3]