Chapter 4 of 21
Environment Setup & Tooling
Current Study Module
Variables & Data Types
Control Flow & Conditionals
Chapter 03 • Memory & Type System

Python Variables, Memory Architecture & Data Types

In C and Java, variables are typed storage buckets holding raw bytes. In Python,everything is an allocated object on the heap, and variables are lightweight pointer tags. Learn how CPython represents objects, why immutability protects data integrity, and how to write type-safe modern Python.

1. Variables are Reference Pointers, Not Memory Boxes

When you assign x = [1, 2, 3], Python does not create a container named x. Instead, it allocates a list object on the heap and binds the label x as a reference pointer to that object. If you assign y = x, both variables point to the exact same physical heap address!

# Mutability Demonstration
a = [10, 20, 30]
b = a  # b points to the same object in memory!

b.append(40)

print(a)  # Output: [10, 20, 30, 40] -> 'a' changed because 'b' modified the shared heap object!
print(id(a) == id(b))  # True (Both share identical memory address)

2. Mutable vs Immutable Types

Understanding mutability is crucial to avoid subtle bugs when passing parameters into functions:

CategoryData TypesMemory Behavior
Immutableint, float, str, tuple, bool, bytes, frozensetCannot be modified in-place after creation. Any modification allocates an entirely new object in memory.
Mutablelist, dict, set, bytearray, custom classesCan be modified in-place (append, update, pop) without changing the object's memory address.
# Immutability in action
s = "hello"
print(id(s))  # e.g. 140238120

s += " world"  # Allocates a new string object!
print(id(s))  # Different memory address!

3. Identity (is) vs Equality (==) & Small Integer Interning

There is a fundamental difference between checking if two objects have the same value versus checking if they are the exact same object in RAM:

  • == compares values (calls the object's __eq__ method).
  • is compares memory addresses (evaluates id(a) == id(b)).
# Small Integer Interning (-5 to 256)
# CPython pre-allocates an array of integer objects from -5 to 256 at startup for speed!
x = 250
y = 250
print(x is y)  # True! Both point to CPython's pre-allocated singleton.

# Outside the interned range:
a = 1000
b = 1000
print(a == b)  # True (Same numerical value)
print(a is b)  # False (Two distinct PyObject allocations in memory!)

4. Modern Python 3.12+ Static Type Annotations

While Python remains dynamically typed at runtime, modern production codebases use Type Hints (PEP 484, PEP 604)for static type analysis using tools like mypy and pyright:

from typing import Optional, List, Dict, Union

# Modern Python 3.10+ Union syntax using pipe operator (|)
def process_user_order(
    user_id: int,
    item_codes: list[str],
    discount_rate: float = 0.0,
    coupon: str | None = None  # Replaces Optional[str]
) -> dict[str, float | str]:
    total = len(item_codes) * 49.99 * (1 - discount_rate)
    return {
        "user": str(user_id),
        "total": round(total, 2),
        "status": "APPROVED" if coupon else "STANDARD"
    }

order = process_user_order(1042, ["A10", "B22"], discount_rate=0.1)
print(order)

Explore Related Tools

Hand-picked utilities and calculators related to this tool.

Related Tools