Lesson · Language Fundamentals
Variables, Names & Binding
69 min readVariables, Names & Binding
In Python, variables are names bound to objects, not boxes that contain values. This single model explains aliasing, mutation, argument passing, identity, and many common surprises.
Learning goals
- Explain assignment as binding a name to an object, and show that rebinding leaves the old object alone.
- Predict what every alias sees after a mutation through one name, such as
b.append(3)becoming visible througha. - Use
a, b = b, aand chained assignment such asa = b = [], and say what the two forms do differently. - Test identity with
isandid(), and tell identity from equality in a concrete example. - Trace where a name resolves through local, enclosing, global, and builtin scopes, and read the
NameErrorwhen it resolves nowhere.
Mental model
The diagram is the lesson's central claim: assignment draws an arrow from a name to an object, and since two names can point at one object, mutating that object is visible from both. Rebinding, by contrast, moves only one arrow (b = [9]), which is why the worked example ends with two independent lists.
Names are arrows, not boxes
two names, one object; then a rebind moves a single arrow
Mental model
the same mechanism as a compact list
name ─────→ object
↑
other_name ──┘Core idea
Assignment in Python never copies a value into a variable: it binds a name to an object, and the object keeps living while at least one name or container references it. The rest of the lesson follows from that picture: aliasing appears when several names reach one object, is compares those arrows, and del removes a name rather than a value.
Variables are names, not boxes
A Python variable is best modeled as a name bound to an object. Assignment changes bindings; it does not automatically copy objects or change the type of a storage box.
Name binding and rebinding
Assignment binds a name to an object. A later assignment can rebind the same name without modifying the previously referenced object.
Multiple assignment
Python can bind several targets in one statement, such as x, y = 1, 2. The right side is evaluated before the new target bindings are completed.
Chained assignment
A chained assignment such as a = b = [] binds both names to the same single object. With mutable objects, that shared identity is often the important consequence.
Swap syntax
Python swaps values naturally with unpacking: a, b = b, a. Both right-side expressions are evaluated before the target names are rebound.
Object identity
id() exposes an implementation-level identity token for an object during its lifetime. Use is for identity tests, especially for singletons such as None, rather than comparing id() values directly.
id()
id(object) returns an integer that identifies the object during its lifetime; two objects that exist at the same time never share an id, but ids can be reused after garbage collection. Use is to test identity in code, and id() mainly for debugging and demonstrations.
Aliasing
Aliasing occurs when multiple names refer to the same mutable object. A mutation through one alias is visible through the others because there is still only one object.
Name lookup basics
When Python evaluates a bare name, it searches the local scope, then any enclosing function scopes, then the module globals, then the builtins, and raises NameError if all four come up empty. Assigning to a name inside a function makes it local for that whole function unless global or nonlocal says otherwise.
del
del name removes the binding between a name and its object; it does not delete the object itself, which stays alive while any other name or container references it. Deleting an unbound name raises NameError, and del items[0] removes an item through the container's __delitem__.
Walkthrough
a = [1, 2]bindsato a new list object, andb = abinds the same object to a second name, producing an alias rather than a copy.b.append(3)mutates the one shared list, soprint(a)shows[1, 2, 3]even thoughanever appears in the call;a is bisTruebecause both names still point at a single object.b = [9]rebinds onlybto a fresh list;akeeps pointing at the first list, so the final line prints two different objects.- Predict before running: what
print(a)shows after the append, whethera is bstaysTrueafter the rebind, and which object each name references on the last line.
Experiments to try
- Replace
b.append(3)withb = b + [3]and rerun: the expression builds a new list and rebindsb, soastays[1, 2]. Explain the difference fromappend. - Add
c = a[:]before the append, mutatec, and show thatais unchanged whilea is cisFalse; then setc = ainstead and watch both change together. - Bind
a = [1], aliasb = a, then rundel aand checkprint(b): the name disappears while the object survives through the other name. - Compare
print(a == [1, 2, 3])withprint(a is [1, 2, 3])and explain why equal values need not be the same object.
Playable lesson
Lab: Names, binding, and mutability
Show names as arrows to objects. Let the learner rebind a name or mutate the shared object and predict what every alias observes.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Names and objects
Objects
nothing allocated yet
Names
no names bound
A name is not a box. Each assignment below draws an arrow from a name to an object; nothing is copied. Step through and predict what every other name sees.
Common mistakes
- Thinking assignment copies an object:
b = agives both names the same list, sob.append(3)shows up ina; only an explicit copy such asa[:]orlist(a)keeps the two independent. - Using
iswhen value equality is intended:isasks whether two names reference one object, so two equal strings built differently can be==but notis. Use==for values and reserveisforNoneand other singletons. - Forgetting that a mutation through one alias affects all aliases: in-place methods such as
appendandsortact on the one shared object, which makes changes appear far from the call site. - Reassigning a name inside a function and expecting the caller to see it: the parameter is a new local name bound to the same object, so mutating the object is visible to the caller while rebinding the name is not.
Practice: Easy
- Run the worked example and record the three prints; change
b = atob = list(a)and record what changes and why. - In the REPL, bind
a = [1, 2], aliasb = a, and showa is b; rebindb = [1, 2]and show it again. Explain the flip with the words binding and object. - Swap two variables with
a, b = b, aand then with three lines using a temporary variable; confirm both produce identical final values.
Practice: Medium
- Predict and verify this sequence:
x = [1],y = [x, x],x.append(2),print(y). Explain the output using one object and three references. - Compare
[[]] * 2with[[], []]: append to the first inner list of each and state which form shares one inner object between the outer slots. - Write two functions, one that does
items.append(value)and one that doesitems = items + [value]; call both on the same list and explain which change the caller can observe.
Practice: Hard
- Trace the worked example with an identity table: one row per statement, columns for each name and the
id()of the object it references. Annotate where an id repeats. - Design a demonstration where
==isTruebutisisFalse(two equal lists) and one where the reverse is the only sensible check (None); explain each result in terms of objects. - Describe what happens when a function assigns
items = []to a parameter that was passed a list, and why the caller's list is unchanged; use the terms local name and caller name.
Lesson checklist
- I can explain assignment as binding a name to an object and show it with
idoris. - I can predict what every alias sees after a mutation through one name.
- I can distinguish rebinding (
b = [9]) from mutating (b.append(9)) in the worked example. - I can say why
isand==can disagree and when each is appropriate.
Remember
Names point at objects; assignment moves an arrow, and mutation changes what the arrow points to. Once `b = a` reads as "two names, one object", aliasing, `is`, `del`, and the surprises around shared lists all follow from the same picture.
Interview angles
What is the main purpose of **Variables are names, not boxes**?+
A Python variable is best modeled as a name bound to an object. Assignment changes bindings; it does not automatically copy objects or change the type of a storage box.
What should you pay attention to when using **Name binding and rebinding**?+
Assignment binds a name to an object. A later assignment can rebind the same name without modifying the previously referenced object.
How does **Multiple assignment** fit into this lesson?+
Python can bind several targets in one statement, such as x, y = 1, 2. The right side is evaluated before the new target bindings are completed.
Why does `b = a` followed by `b.append(3)` change what `a` shows?+
b = a binds two names to one list object, so the append runs against that shared object and reading a afterwards shows the mutation. A copy such as b = a[:] would have kept the two lists independent.