Topic 27 of 64
Variable Allocation
Overview
Python variables are labels (references) that point to objects in memory — not boxes that store values. Understanding this reference model prevents subtle bugs with mutable objects and explains how assignment works.
Syntax
python
# Assignment creates a reference
x = 10
y = x # y points to same object as x
# Variables are case-sensitive
name = "Alice"
Name = "Bob" # different variable
# Multiple assignment
a = b = c = 0
# Tuple unpacking
x, y, z = 1, 2, 3Common Pitfalls
- Never name variables after Python builtins: list, dict, str, type, id — this shadows them.
- For deep copies of nested structures use 'import copy; copy.deepcopy(obj)'.
- Interview tip: Explain id() — it returns the memory address of an object, proving two variables point to the same object.
Real-World Example
Demonstrating reference semantics with mutable lists
example
python
a = [1, 2, 3]
b = a # both point to same list
b.append(4)
print(a) # [1, 2, 3, 4] — a is affected!
# To get independent copy:
c = a.copy()
c.append(5)
print(a) # [1, 2, 3, 4] — unchanged