Learning Objectives
- Explain why Python variables are labels referencing objects rather than fixed memory boxes.
- Identify immutable (`int`, `str`, `tuple`, `frozenset`) vs mutable (`list`, `dict`, `set`) types.
- Avoid aliasing bugs and shared mutable default parameters across functions and dataclasses.
Prerequisites
- Python 3.12 installed locally (`python3 --version`)
Names Point to Objects in Python
Writing b = a in Python does not copy data — it binds two names to the exact same object in memory. If that object is immutable (int, str, tuple), reassigning b += 1 simply binds b to a new integer object cleanly. If that object is mutable (list, dict), calling b.append(...) mutates what a sees as well.
Explore how Python powers RAG AI Systems, try Python Topic Mock Tests, or join the Python Backend Career Program.
Practical Programming Examples
Safe Mutable Defaults & Type-Hinted Dataclass in Python 3.12
Replace a shared mutable default argument bug with None-guarded initialization and dataclasses.field.
from dataclasses import dataclass, field
def enroll_tracks(track: str, enrolled: list[str] | None = None) -> list[str]:
target = [] if enrolled is None else enrolled.copy()
target.append(track)
return target
@dataclass(slots=True)
class LearnerProfile:
student_code: str
skills: list[str] = field(default_factory=list)
first = enroll_tracks("Django 5")
second = enroll_tracks("FastAPI")
print("Isolated lists:", first, second)
Isolated lists: ['Django 5'] ['FastAPI']
- Using `enrolled: list[str] | None = None` allocates a clean fresh list on every independent invocation.
- `@dataclass(slots=True)` reduces per-instance memory overhead while `field(default_factory=list)` prevents shared state.
Common Mistakes to Avoid
- Initializing `items: list = []` in function signatures or mutable class attributes.
- Comparing strings/large integers using `is` (object identity) instead of `==` (value equality).
Production Best Practices
- Use `is None` / `is not None` exclusively for `None` checks; use `==` for values.
- Annotate modern Python 3.12 signatures (`list[str] | None`) cleanly for `mypy` and `ruff` checks.
Technical Interview Relevance
Guaranteed Python fresher/backend question covering `is` vs `==`, mutable default arguments, and `copy` vs `deepcopy`.
Practice & Self-Check Questions
Why does `[[]] * 3` cause unexpected behavior in Python?
Multiplying a list of lists repeats references to the exact same inner list three times; modifying `grid[0].append(1)` mutates all rows. Use `[[ ] for _ in range(3)]`.