Part 02 / Topic 1 of 10
Variables and memory
A variable is a name that points to an object in memory. Think of a sticky label on a box: the box (the object) holds the value, the label is the name. Every object has a value and a type (what kind of data it is). id() shows the object's identity (in CPython, its memory address).
==checks: are the values equal?ischecks: is it the same object?
Real-world example: Two people share one shopping list (same object) vs each has a copy (equal, but different objects).
([...] is a list, taught in Part 4. For now: it holds many items, and .append() adds one.)
list_a = ["milk", "bread"]
shared = list_a # same object, two names
copy_b = ["milk", "bread"] # new object, same value
print(list_a == copy_b) # True (same value)
print(list_a is copy_b) # False (different objects)
print(list_a is shared) # True (same object)
print(id(list_a) == id(shared)) # True
shared.append("eggs")
print(list_a) # ['milk', 'bread', 'eggs']
Mutable vs immutable:
| Type | Can change in place? | Examples |
|---|---|---|
| Immutable | ❌ No. A "change" makes a new object | int, float, str, bool, tuple, None |
| Mutable | ✅ Yes | list, dict, set |
Reassignment moves the name to a new object. Other names are not affected.
x = 10
y = x # y points to the same 10
x = x + 1 # x now points to a new object 11
print(x, y) # 11 10
# Swap two values in one line
a, b = 5, 9
a, b = b, a
print(a, b) # 9 5
Naming rules: letters, digits, _; cannot start with a digit; case-sensitive (Age ≠ age). Use snake_case, e.g. total_amount. Write fixed values as UPPER_SNAKE_CASE constants, e.g. GST_RATE = 0.18. Don't use built-in names like list, sum or input as variable names.
🔍 Going deeper: CPython keeps one shared copy of small ints (-5 to 256), so
a = 100; b = 100; a is bisTrue. For big numbers it depends:a = 1000; b = 1000; a is bis usuallyFalsewhen typed as separate lines in the REPL, but can beTruein a script (Python compiles the whole file at once and shares equal constants). That is a speed trick, not a rule, so never useisto compare numbers or strings. Useisonly forNone.
Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.