Iterators and generators

Topic 1 of 2 in Pythonic Python8 min readBeginnerFree course

Overview

You’ve looped over lists, strings, ranges, dictionaries and files. How does one for statement work with all of them — including a 10 GB log file that would never fit in memory? The answer is the iterator protocol, and once you understand it you can write your own lazy sequences with generators.

Iterables and iterators

  • An iterable is anything you can loop over: lists, tuples, strings, dicts, sets, files, range…
  • An iterator is an object that produces the items one at a time and remembers where it is.

iter() gets an iterator from an iterable; next() asks it for the next item:

Python
colours = ["red", "green", "blue"]
it = iter(colours)
next(it)        # 'red'
next(it)        # 'green'
next(it)        # 'blue'
next(it)        # StopIteration

When there’s nothing left, the iterator raises StopIteration. That’s exactly what a for loop does behind the scenes:

Python
# for colour in colours: print(colour)   is roughly:
it = iter(colours)
while True:
    try:
        colour = next(it)
    except StopIteration:
        break
    print(colour)

Iterators are one-way and one-time: once used up, they stay empty. Many built-ins return iterators — zip, map, enumerate, reversed, a file object — which is why printing them shows <zip object at 0x…>, and why list(...) is needed to see the items.

Generator functions: yield

Writing an iterator class by hand is possible but tedious. A generator function is much simpler: a normal function that uses yield instead of (or as well as) return.

Generators produce values one at a time. def countdown(n): while n > 0: yield n, then n -= 1. for x in countdown(3): print(x) prints 3 2 1. The first next() runs until yield, giving 3; the second resumes after the yield, giving 2; the third resumes, giving 1; the fourth finds the function has ended and raises StopIteration. A generator remembers where it paused. It never builds the whole list, so it can handle huge files or endless streams with tiny memory. for loops call next() and stop at StopIteration.

Python
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)          # 3, 2, 1

How it works:

  1. Calling countdown(3) doesn’t run the body. It returns a generator object (an iterator).
  2. Each next() runs the body until the next yield, hands out that value, and pauses — keeping all its local variables.
  3. The next next() resumes right after the yield.
  4. When the function ends, the generator raises StopIteration, and the for loop stops.

Compare it with building a list:

Python
def countdown_list(n):
    result = []
    while n > 0:
        result.append(n)
        n -= 1
    return result

Same output, but the list version builds every item in memory first. The generator produces each one only when asked.

Why generators matter

Huge data with tiny memory

Python
def read_lines(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.rstrip("\n")

This processes a file of any size using memory for just one line at a time.

Infinite sequences

A generator can go on forever — the caller decides how much to take:

Python
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

from itertools import islice
list(islice(fibonacci(), 10))    # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

A list version would never finish.

Stopping early is free

any(), next() and break stop asking for items as soon as they have an answer, so a generator does only the work that’s needed:

Python
first_big = next(n for n in fibonacci() if n > 1000)    # 1597

Generator pipelines

Generators that take an iterable and yield transformed items can be chained, like Unix pipes. Each item flows through the whole pipeline before the next is read:

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

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

for msg in messages(errors(read_lines("app.log"))):
    print(msg)

Each stage is small, testable and reusable — and the whole pipeline uses constant memory.

Generator expressions

You met these in Comprehensions: round brackets make a lazy generator instead of a list.

Python
squares = (n * n for n in range(1_000_000))   # nothing computed yet
total = sum(squares)                           # computed one at a time

Use a generator expression for simple one-line transformations, a generator function when you need statements, state, or several yields.

yield from

A generator can hand over to another iterable with yield from:

Python
def all_lines(paths):
    for path in paths:
        yield from read_lines(path)

Gotchas

  • One use only: after looping over a generator, it’s exhausted. Looping again gives nothing, silently. If you need the items twice, make a list — or call the generator function again.
  • No len() or indexing: generators don’t know how many items they’ll produce. Convert with list() if you need those (and the data fits in memory).
  • Errors happen late: since the body runs only when iterated, a bug inside shows up during the loop, not when you call the function.

Useful itertools for iterators

Python
from itertools import islice, chain, count, takewhile, pairwise

list(islice(count(10, 5), 3))                 # [10, 15, 20] — count() is infinite
list(chain("ab", [1, 2]))                     # ['a', 'b', 1, 2]
list(takewhile(lambda n: n < 10, fibonacci()))   # [0, 1, 1, 2, 3, 5, 8]
list(pairwise([1, 4, 9]))                     # [(1, 4), (4, 9)]

The big idea: a generator is a function that pauses. Use one whenever you’d build a big list only to loop over it once.

Exercise

A log-processing pipeline

Your program first writes a small log file (in the starter). Then build a pipeline of generators: (1) read_lines(path) yields each line without its newline; (2) errors(lines) yields only lines containing ERROR; (3) messages(lines) yields the text after the third space-separated field (the message). Print every error message. Then (4) write an infinite generator fibonacci() and print the first 10 numbers using itertools.islice; and (5) show how next() works by calling it three times on countdown(3) and catching the StopIteration from a fourth call.

Python
from itertools import islice

with open("app.log", "w", encoding="utf-8") as f:
    f.write(
        "2026-12-04 10:00:01 INFO Server started\n"
        "2026-12-04 10:00:05 ERROR Database timeout\n"
        "2026-12-04 10:01:17 INFO User asha logged in\n"
        "2026-12-04 10:02:42 ERROR Payment declined for order 1042\n"
    )

# 1–3. Generator pipeline

# 4. Fibonacci

# 5. next() and StopIteration
def countdown(n):
    while n > 0:
        yield n
        n -= 1

Summary

  • An iterable (list, string, file, dict…) can give an iterator with iter(); an iterator hands out items one at a time with next().
  • A for loop calls iter() once, then next() repeatedly until StopIteration.
  • A function containing yield is a generator: calling it returns an iterator that runs the body lazily, pausing at each yield.
  • Generators use almost no memory, so they handle huge files and infinite sequences; but they can only be looped over once.
  • Chain generators into pipelines, and use itertools (islice, chain, …) to slice and combine them.