Every for loop in Python runs on iterators: objects that hand out one value at a time. Generators are the easy way to write your own: a normal function that uses yield instead of return. Because generators produce values only when asked, they can work through huge or even endless sequences while using almost no memory.
In this lesson you will learn
- The difference between an iterable and an iterator
- How
iter(),next()andStopIterationwork - How to write an iterator class
- How
yieldturns a function into a generator - Why generators save memory
Iterables and Iterators
An iterable is anything you can loop over: a list, string, dict or file. Calling iter() on it gives an iterator, which remembers its position. Each next() returns the following value, and StopIteration signals the end.
colors = ["red", "green"]
it = iter(colors)
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("No more items")
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
print(list(Countdown(3)))
Output
red
green
No more items
[3, 2, 1]
A for loop does exactly this for you: it calls iter() once, then next() repeatedly, and stops quietly at StopIteration. To make your own iterator class, give it __iter__ (return self) and __next__ (return the next value or raise StopIteration), as Countdown does.
Generators with yield
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3)))
def fibonacci():
a, b = 0, 1
while True: # infinite, but values are made on demand
yield a
a, b = b, a + b
fib = fibonacci()
print([next(fib) for _ in range(8)])
import sys
big_list = [n for n in range(100000)]
big_gen = (n for n in range(100000))
print(sys.getsizeof(big_list) > 100000, sys.getsizeof(big_gen) < 1000)
print(sum(big_gen))
Output
[3, 2, 1]
[0, 1, 1, 2, 3, 5, 8, 13]
True True
4999950000
- A function containing
yieldreturns a generator when called. The body does not run yet. - Each
next()runs the body until the nextyield, hands out that value, and pauses there with all local variables kept. countdowndoes the same job as the 10-lineCountdownclass in 4 lines.fibonacci()loops forever, which is safe because values are only made when requested.- The list of 100,000 numbers takes hundreds of kilobytes; the generator expression takes a couple of hundred bytes, whatever its length.
A generator can be used only once
After sum(big_gen) consumed every value, looping over big_gen again gives nothing. Call the generator function again for a fresh one.
List vs Generator
| List | Generator | |
|---|---|---|
| Values stored | All at once | One at a time |
| Memory | Grows with size | Small and constant |
| Reusable | Yes | No, single pass |
Indexing (x[3]) | Yes | No |
| Good for | Small data you reuse | Big files, streams, pipelines |
Common Mistakes
- Looping over a used-up generator and getting nothing.
- Calling
len()on a generator. It has no length; convert withlist()first if it is small. - Using
return valueinstead ofyield value, which ends the generator immediately. - Turning an infinite generator into a list, which never finishes.
Practice Exercises
Exercise 1. Write a generator evens(limit) that yields even numbers up to limit.
Show answer
def evens(limit):
for n in range(0, limit + 1, 2):
yield n
print(list(evens(10))) # [0, 2, 4, 6, 8, 10]
Exercise 2. Read a large log file and count the lines containing “ERROR” without loading it all into memory.
Show answer
with open("app.log") as f:
print(sum(1 for line in f if "ERROR" in line))
File objects are iterators, and the generator expression reads one line at a time.
Frequently Asked Questions
What is the difference between yield and return?
return sends back one value and ends the function. yield sends back a value and pauses, so the function can continue from the same point next time.
What is yield from?
yield from other yields every value from another iterable, which saves writing a loop that yields each item.
Summary
- Iterables give iterators; iterators hand out values with
next(). StopIterationmarks the end, andforhandles it for you.yieldmakes a generator that pauses between values.- Generators use little memory but can be consumed only once.
Next: Python Decorators.
