python / python-functions
16 mins
Python Level 5: Idiomatic List & Dict Comprehensions
Why This Matters: Comprehensions provide concise, highly-optimized expressions for constructing new lists and dicts.
## Idiomatic Python Comprehensions
List comprehensions replace multi-line append loops with a single expressive line.
```python
# Traditional Loop
evens = []
for x in range(10):
if x % 2 == 0:
evens.append(x)
# Idiomatic List Comprehension
evens = [x for x in range(10) if x % 2 == 0]
```
MENTAL MODEL & MEMORY LAYOUT
COMPREHENSION PIPELINE: [ Expression (x*2) ] for [ Item x ] in [ Iterable ] if [ Filter Condition ]
COMMON PITFALLS TO AVOID
- Writing overly complex nested comprehensions that harm readability.
Dictionary Comprehension Pattern
words = ["code", "python"]
lengths = {w: len(w) for w in words}
print(lengths) # {'code': 4, 'python': 6}Constructs a key-value dictionary mapping string items to their calculated character lengths.
CONCEPT MASTERY CHECKPOINT
Which expression constructs a list of squared numbers for x from 0 to 4?
NEXT RECOMMENDED LESSON
Python Level 6: Files & Exceptions
Challenge: Write a dict comprehension mapping list of words to their length.