~/learn/Python · Iteration & generators

Comprehensions and generators

Lazy iteration for large or infinite sequences.

8 min readlesson 12 of 23generatoryielditertools

why this matters

Loops process data item by item; comprehensions do the same in one readable line.

A generator function uses yield to produce values one at a time, keeping memory flat no matter how long the sequence is.

python · editable
loading editor…

A generator expression looks like a comprehension in round brackets and pairs well with sum, any, all and max.

python · editable
loading editor…

itertools adds ready-made building blocks: islice to take the first N, chain to flatten, groupby to bucket sorted data.

python · editable
loading editor…

Reading a comprehension

[p * 2 for p in prices if p > 5]
  │         │             └─ keep only these
  │         └─ for each item
  └─ what to produce

key takeaways

  • for x in items: runs once per item.
  • Comprehensions build lists in one line.
  • enumerate gives index + item; zip pairs lists.

check your understanding

What is [n * n for n in range(4)]?

free practice

Build confidence with a question you can solve without Pro.