Lesson 1 of 9 · 18m
Iteration the Pythonic Way
for loops over iterators, comprehensions that read like sentences, and when the one-liner is wrong.
Python's superpower is that for works on iterators — anything that can produce its items one at a time. That is why for line in file, for key, value in dict.items(), and for i, name in enumerate(names) all read the same way. The loop does not care what it walks over. Once you think in iterators, half the awkward patterns disappear.
Comprehensions: the readable one-liner
# The classic pattern every beginner writes
active = []
for user in users:
if user.is_active:
active.append(user.email)
# The same thing, Pythonic
active = [user.email for user in users if user.is_active]A comprehension is a map-and-filter sentence: [transform for item in sequence if condition]. It reads left to right like English and produces a new list — no mutation, no temporary append loop.
When the one-liner becomes a lie
Comprehensions are for transforming and filtering. The moment you need a side effect, a second loop, or more than one condition with a name for each, write the loop. This is fine:
for user in users:
if user.is_active and not user.is_suspended:
activate_membership(user)
send_confirmation(user.email)A nested [(x, y) for x in xs for y in ys] that takes you three reads to parse is not Pythonic — it is just short.
Generators: lazy by default
# A list of a million rows in memory
rows = [process(r) for r in file]
# The same work, one row at a time
rows = (process(r) for r in file)Parentheses instead of brackets makes a generator — same syntax, but items are produced on demand. For large or streamed data this is the difference between "works in the notebook" and "works in production."
Try it yourself
// The comprehension idea, in JavaScript — same map/filter logic:
const users = [{active:true,email:"a@x"},{active:false,email:"b@x"},{active:true,email:"c@x"}];
const emails = users.filter(u => u.active).map(u => u.email);
console.log(emails);::exercise(sum-of-squares)
The rule
Iterate lazily, transform with comprehensions, and write the loop out the moment the one-liner takes a second read.