Learn / Intermediate / Lesson 6

Iterators and generators

12 min Tested on Python 3.15Updated By
In short

An iterator hands out values one at a time with next() until it raises StopIteration; every for loop uses one behind the scenes. A generator is the easy way to write your own iterator: a function that uses yield instead of return. Generators are lazy, so they can process huge files or endless streams with almost no memory.

What a for loop really does

Python
colours = ["red", "green"]
it = iter(colours)
print(next(it))
print(next(it))
try:
    next(it)
except StopIteration:
    print("No more items")
Output
red
green
No more items

A list is iterable: iter() can make an iterator from it. for colour in colours calls iter() once, then next() until StopIteration. Strings, dicts, files and ranges all work the same way.

Generator functions

Python
def countdown(start: int):
    print("Starting")
    while start > 0:
        yield start
        start -= 1
    print("Lift-off!")

for n in countdown(3):
    print(n)
Output
Starting
3
2
1
Lift-off!
  • Calling countdown(3) runs nothing yet — it returns a generator object.
  • Each next() runs the function until the next yield, then pauses there.
  • When the function ends, the generator raises StopIteration for you.

Lazy means memory-friendly

Python
import sys

squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))
print(sys.getsizeof(squares_list) > 1_000_000)
print(sys.getsizeof(squares_gen) < 1_000)
print(sum(squares_gen))
Output
True
True
333332833333500000

Pipelines of generators

Python
log_lines = [
    "INFO start",
    "ERROR disk full",
    "INFO retry",
    "ERROR timeout",
]

def errors(lines):
    for line in lines:
        if line.startswith("ERROR"):
            yield line

def messages(lines):
    for line in lines:
        yield line.split(" ", 1)[1]

for msg in messages(errors(log_lines)):
    print(msg)
Output
disk full
timeout

Each stage handles one line at a time, so this works the same for 4 lines or a 40 GB log file read with open().

Infinite generators and itertools

Python
import itertools

def ids(prefix: str):
    n = 1
    while True:
        yield f"{prefix}-{n:03}"
        n += 1

print(list(itertools.islice(ids("ORD"), 3)))

for size, colour in itertools.product(["S", "M"], ["red", "blue"]):
    print(size, colour)

print(list(itertools.batched(range(7), 3)))
Output
['ORD-001', 'ORD-002', 'ORD-003']
S red
S blue
M red
M blue
[(0, 1, 2), (3, 4, 5), (6,)]

islice takes the first few values from any iterator, product builds every combination, and batched (Python 3.12+) splits data into chunks — handy for sending records to an API in groups.

Practice

Write a generator evens(limit) that yields the even numbers from 0 up to and including limit. Print list(evens(10)), then the sum of evens(100).

Expected output:
[0, 2, 4, 6, 8, 10]
2550
Your code

Quick check

1. What does calling a generator function return?

2. What happens if you loop over the same generator twice?

3. Why use a generator for a huge file?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →