Python Variables and Reference Assignment Practice
Understanding how variables bind to objects in memory is the foundation of Python mastery. Unlike C or Java where variables act as fixed memory buckets, Python variables act as name labels attached to objects. Tracing rebinding and chained assignment ensures you never misjudge variable states.
Core Conceptual Insights
Theoretical Blueprint:Think of a Python variable like a adhesive name tag rather than a wooden box. When you assign `x = 10`, you attach the tag `x` to the integer object `10`. If you later write `x = 20`, you detach the tag `x` from `10` and stick it onto `20` without modifying the original number object.
Common Developer Trap:Beginners often assume chained assignment (`a = b = []`) creates two independent empty lists. In reality, both name labels point to the exact same list object in memory.
Structured Practice Breakdown
Chained assignment shared reference
x = y = [1, 2] x.append(3) y = [4, 5] print(x, y)
[1, 2, 3] [4, 5]Execution Walkthrough
First, x and y share `[1, 2]`. `x.append(3)` mutates that shared list to `[1, 2, 3]`. Then `y = [4, 5]` rebinds y to a separate new list. Output is `[1, 2, 3] [4, 5]`.
Tuple unpacking variable swap
a, b = 10, 20 a, b = b + 5, a - 5 print(a, b)
25 5Execution Walkthrough
The right-hand side evaluates `(20 + 5, 10 - 5) -> (25, 5)` using initial `a=10, b=20`. Then `a` receives `25` and `b` receives `5` simultaneously.
Augmented assignment vs rebinding
num = 5 num = num * 2 + 3 print(num)
13Execution Walkthrough
Python evaluates `num * 2 + 3` as `(5 * 2) + 3 = 13`, and assigns that new integer object back to variable `num`.
Extended unpacking (`*` syntax)
first, *rest, last = [10, 20, 30, 40, 50] print(rest)
[20, 30, 40]Execution Walkthrough
`first` captures `10` at index 0, and `last` captures `50` at index -1. The starred target `*rest` captures all remaining middle items as a list: `[20, 30, 40]`.