Lesson 32 of 34 · Errors & Pythonic Tools
Python Iterators and Generators
A for loop works on lists, strings, dictionaries, files and ranges alike. The secret behind that is the iterator protocol. Once you understand it, you can write generators — functions that produce values lazily, one at a time, which lets you process huge or even infinite sequences without running out of memory.
Iterables and iterators
An iterable is anything you can loop over. Calling iter() on it returns an iterator — an object that hands out one item each time you call next(), and raises StopIteration when it runs out:
letters = iter(["a", "b"])
print(next(letters)) # a
print(next(letters)) # b
print(next(letters, "done")) # done (a default instead of StopIteration)
A for loop does exactly this behind the scenes: it calls iter() once, then next() repeatedly until StopIteration tells it to stop.
Generator functions
A function that contains yield is a generator function. Calling it doesn't run its body — it returns a generator object. Each next() runs the body until the next yield, hands out that value, and pauses, remembering all its local variables:
def three_steps():
print("step 1")
yield 1
print("step 2")
yield 2
print("step 3")
yield 3
steps = three_steps() # nothing printed yet!
print(next(steps)) # prints "step 1", then 1
print(next(steps)) # prints "step 2", then 2
Generators work everywhere iterables do — in for loops, list(), sum(), max() and comprehensions:
def evens(limit):
n = 0
while n <= limit:
yield n
n += 2
print(list(evens(8))) # [0, 2, 4, 6, 8]
print(sum(evens(100))) # 2550
Lazy evaluation
A list stores all its items in memory at once. A generator produces each value only when asked. That makes generators ideal for reading huge files line by line, for pipelines that transform data step by step, and even for infinite sequences:
def forever(start):
while True:
yield start
start += 1
An infinite generator is perfectly safe — as long as whoever consumes it stops at some point. list(forever(1)) would never finish.
Generator expressions
Swap the square brackets of a list comprehension for parentheses and you get a generator expression. When it's the only argument of a function, you can even drop the extra parentheses:
squares = (n * n for n in range(1_000_000)) # nothing computed yet
total = sum(n * n for n in range(1_000_000)) # no million-item list in memory
longest = max(len(word) for word in ["fire", "ice", "thunder"]) # 7
Generators are single-use
Once a generator is exhausted, it stays empty:
nums = (n for n in range(3))
print(list(nums)) # [0, 1, 2]
print(list(nums)) # []
Need the values twice? Create a new generator, or store the results in a list.
Helpful tools
The itertools module is full of iterator building blocks: itertools.count(1) counts forever, itertools.islice(gen, 5) takes the first five items of any iterator, and itertools.chain(a, b) joins iterables. Inside a generator, yield from other yields every item of another iterable.
Common mistakes
- Expecting a list:
countdown(3)returns a generator object. Wrap it inlist()to see all values at once. - Consuming a generator twice — the second pass finds nothing.
- Calling
list()on an infinite generator, which never returns. - Using
return valueinstead ofyield value—returnends the generator.
Assignment
Write two generator functions and one helper:
countdown(n)is a generator that yieldsn,n - 1, … down to1. It yields nothing whennis0or less.fibonacci()is an infinite generator of Fibonacci numbers:0, 1, 1, 2, 3, 5, 8, …— each number is the sum of the previous two.take(iterable, n)returns a list with the firstnitems of any iterable (fewer if it runs out). It must work with infinite generators, so it may only pull the items it needs.
list(countdown(3)) # [3, 2, 1]
take(fibonacci(), 8) # [0, 1, 1, 2, 3, 5, 8, 13]
take("hiss", 2) # ["h", "i"]
take([1, 2], 5) # [1, 2]Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .