List Comprehensions & Functional Programming
Transform data with comprehensions, map/filter, and lambda expressions idiomatically.
Comprehensions
List comprehensions [f(x) for x in items if pred(x)] replace verbose loops. Dict and set comprehensions build mappings and unique collections similarly.
Keep comprehensions readable—nested comprehensions beyond two levels often deserve explicit loops.
Comprehensions are eager; generator expressions defer computation for streaming pipelines.
- Do not sacrifice readability for one-line comprehensions
- Use walrus := inside comprehensions sparingly for clarity
- Prefer sum(1 for x in items if cond) over len([...])
active_emails = [u.email for u in users if u.is_active]
index = {p.sku: p for p in products}map, filter, and reduce
map applies a function to iterables; filter keeps truthy results. functools.reduce folds sequences to a single value.
In Python 3, list comprehensions often read clearer than map/filter for simple transforms. reduce is less common than explicit loops or sum/max builtins.
Use operator module functions like itemgetter for sorting complex objects.
- Builtins like sum, any, all are faster than manual reduce
- Avoid lambda in map when def named functions clarify intent
- Chain transformations with intermediate named variables when debugging
from functools import reduce total = sum(p.price for p in products) longest = max(words, key=len)