Skip to main content
Albero Academy

Iterators, Generators & Comprehensions

How Python loops under the hood — the iterator protocol, memory-efficient generators with yield, and expressive comprehensions.

Chapter 14Python18 min readBeginner friendly
  • #Python
  • #Generators
  • #Iterators

Every for loop you've written uses the iterator protocol. Understanding it unlocks generators — a way to produce values lazily, one at a time, so you can process huge (even infinite) sequences without loading them into memory. This is the Pythonic path to fast, memory-light data code.

Iterables & iterators

An iterable is anything you can loop over (a list, string, dict, file). When you loop, Python calls iter() to get an iterator, then next() repeatedly until it raises StopIteration:

what a for loop really does
nums = [10, 20, 30]
it = iter(nums) # get an iterator
print(next(it)) # 10
print(next(it)) # 20
# ...until StopIteration
# The for loop is just this, tidied up:
for n in nums:
print(n)

Generators & yield

A generator is a function that produces a series of values with yield instead of returning once. Each yield hands back a value and pauses the function, resuming where it left off on the next request. Values are computed on demand, so memory stays flat no matter how many there are:

a generator
def countdown(n):
while n > 0:
yield n # produce a value, then pause
n -= 1
for x in countdown(3):
print(x) # 3, 2, 1
# Lazy: this never builds a billion-element list
def naturals():
n = 1
while True: # infinite — but fine, it's lazy
yield n
n += 1

Generator expressions

A generator expression looks like a list comprehension with parentheses instead of brackets — same syntax, but lazy. Perfect as an argument to sum, max, any:

lazy one-liners
# List comprehension — builds the whole list in memory
squares = [n * n for n in range(1000)]
# Generator expression — computes on demand, no list built
total = sum(n * n for n in range(1_000_000)) # memory-light
any(s.placed for s in students)

Comprehensions

Comprehensions build a collection from an iterable in one readable line. They come in three flavours:

list / dict / set comprehensions
nums = [1, 2, 3, 4, 5]
# List — transform + filter
evens_sq = [n * n for n in nums if n % 2 == 0] # [4, 16]
# Dict — build key/value pairs
lengths = {w: len(w) for w in ["excel", "sql"]} # {'excel': 5, 'sql': 3}
# Set — unique results
first_letters = {w[0] for w in ["sql", "scala", "python"]} # {'s', 'p'}

itertools

The standard-library itertools module is a toolbox of fast, lazy iterator building blocks:

handy itertools
from itertools import chain, groupby, count, islice
list(chain([1, 2], [3, 4])) # [1, 2, 3, 4] flatten
list(islice(count(1), 5)) # [1, 2, 3, 4, 5] take first 5 of infinite
# groupby, product, combinations, accumulate… all lazy

Practice

Write a generator read_large(path) that yields a file's lines one at a time. Then use a generator expression to count how many lines contain the word "error" — without ever building a list of lines.

Key takeaways

  1. 01for loops use the iterator protocol: iter() then next() until StopIteration.
  2. 02A generator function uses yield to produce values lazily, one at a time — flat memory.
  3. 03Generator expressions are lazy comprehensions with () — ideal for sum/max/any over big data.
  4. 04List/dict/set comprehensions build collections in one readable line (one transform + one filter).
  5. 05itertools provides fast, lazy building blocks (chain, islice, groupby, product…).