python / python-basics
18 mins
Python Level 3: Lists, Mutability & Hash Dictionaries
Why This Matters: Understanding mutable (Lists/Dicts) vs immutable (Tuples/Strings) data structures is crucial in Python.
## Core Python Data Structures
- **List** `[1, 2, 3]`: Ordered, **mutable** sequence.
- **Tuple** `(1, 2)`: Ordered, **immutable** sequence.
- **Set** `{1, 2}`: Unordered collection of **unique** items.
- **Dict** `{"key": "val"}`: Key-value hash map table.
MENTAL MODEL & MEMORY LAYOUT
MUTABILITY MODEL: List [1, 2] ──(append 3)──► Mutates original object in place [1, 2, 3] Tuple (1, 2) ──(modify)──► TypeError! Cannot mutate immutable tuple
COMMON PITFALLS TO AVOID
- Attempting to modify tuple elements (`t[0] = 5` raises TypeError).
- Using mutable lists as dictionary keys.
Dictionary Key-Value Lookup
user = {'name': 'Dev', 'role': 'Engineer'}
user['score'] = 95 # Add key
for k, v in user.items():
print(f"{k}: {v}")Iterates over key-value tuple pairs using dict.items().
CONCEPT MASTERY CHECKPOINT
Which built-in Python collection is IMMUTABLE (cannot be modified after creation)?
NEXT RECOMMENDED LESSON
Python Level 4: Functions & Scope
Challenge: Write a function `get_evens(nums)` returning a list of even numbers from nums.