Python - Names & Binding
Overview
Estimated time: 30–40 minutes
Understand how names refer to objects, the difference between identity and equality, and why mutability matters for program behavior.
Learning Objectives
- Explain names vs objects; identity (
is
) vs equality (==
). - Recognize mutable vs immutable types and side effects.
- Avoid common mutability pitfalls in lists and dicts.
Prerequisites
Identity vs Equality
a = [1, 2]
b = [1, 2]
print(a == b) # equality: True
print(a is b) # identity: usually False
c = a
print(c is a) # True (same object)
Expected Output:
True
False
True
Mutability
nums = [1, 2, 3]
nums.append(4) # mutates list
print(nums)
x = 10
x += 1 # creates a new int object (ints are immutable)
print(x)
Expected Output:
[1, 2, 3, 4]
11
Common Pitfalls
- Using a mutable default argument in a function. Prefer
None
+ initialize inside. - Aliasing: two variables referencing the same list; modifying one affects the other.
Checks for Understanding
- What operator checks identity? What about equality?
- Which of these are immutable: list, tuple, str, dict?
Show answers
is
checks identity;==
checks equality.- tuple and str are immutable; list and dict are mutable.
Exercises
- Write a function that appends to a list argument; observe aliasing if two names refer to the same list.
- Demonstrate the mutable default pitfall and fix it by using
None
.