Module 1: Python First Principles & Environment
1.2 Dynamic Typing, Variables & Memory References
Estimated reading & practice time: ~20 minutes
Learning Objectives
• Understand that variables in Python are name tags (pointers), not memory boxes.
• Distinguish immutable types (int, float, str, tuple) from mutable types (list, dict, set).
• Inspect memory identities with the `is` operator and `id()`.
Mental Model & Analogy
In C or Java, a variable is a cardboard box with a size label where values are stored inside. In Python, a variable is a sticky luggage tag: the value floats in heap memory, and your variable name is just a string tied to that object. Multiple tags can be tied to the exact same object!
Core Concept Breakdown
**Key Python Memory Rules**:
1. **Variables are Pointers**: `a = [1, 2, 3]` binds the name `a` to a heap list object. `b = a` does NOT copy the list; both `a` and `b` point to the identical list!
2. **Immutable vs Mutable**:
• **Immutable**: `int`, `float`, `str`, `tuple`, `frozenset`. Mutating a string creates a new string object.
• **Mutable**: `list`, `dict`, `set`. Modifying in-place alters all variables pointing to it.
3. **`==` vs `is`**:
• `==` checks value equality (`a == b`).
• `is` checks memory identity (`id(a) == id(b)`). Always use `is None` for checking null values.
Architecture Diagram
Code Example
PYTHON Example
# Memory reference demonstration
a = [10, 20]
b = a # b points to the same object
c = [10, 20] # c is a new distinct object with identical content
b.append(30)
print(f"a: {a}")
print(f"b: {b}")
print(f"a == c? {a == c}")
print(f"a is b? {a is b}")
Line-by-Line Walkthrough
• Because `b` and `a` share the same object reference, appending to `b` reflects in `a`.
• `a is b` evaluates to True.
a: [10, 20, 30] b: [10, 20, 30] a == c? False a is b? True
Common Pitfalls & Debugging
• Using mutable default arguments in functions like `def add_item(item, target_list=[]):`: the default list is created ONCE when the module loads and is shared across all function calls! Always use `target_list=None`.
Try It Yourself — Python Sandbox
Live ExecutionUse `copy.deepcopy()` to make an independent copy of a nested list `[[1, 2], [3, 4]]` and verify that modifying the copy does not alter the original.
solution.py
Edit the code and click Run Code to verify output directly inside TBLearn.
1
Terminal Output
Click "Run Code" or press Ctrl+Enter to execute.
Knowledge Checkpoint • Earn +40 Credits
Test Yourself Before Moving Forward
Short, practical questions tied directly to this section. Passing awards Credits toward course discounts and interview packs.
Checkpoint: Python Execution Model & References
Test Python bytecode compilation, reference pointers, and dynamic typing.