Skip to content
Fullstack Launchpad

Python Iterators and Generators #2.2

A for loop takes one item at a time from an iterator. A generator pauses at each yield and resumes when the loop asks for the next item.

By Published Updated 10 min readPython for Engineers Switching Languages

Iterators and generators

What does this code print?

python
squares = (n * n for n in [1, 2, 3])
print(sum(squares))
# prints: 14
print(sum(squares))
# prints: 0

The second call gives 0 because squares is used up. The whole lesson builds on two ideas in that snippet:

  • An iterator keeps its place. sum, list and for all ask for one item at a time with next() until it runs out. Once exhausted, it stays at the end.
  • A generator (here written in round brackets) is a kind of iterator: it computes each value when asked and never builds the whole list.

Each row below is one section of the lesson, with a short example:

SectionExampleResult
Iterable and iteratorit = iter([1, 2]), then next(it)1
Iterator protocolnext(it) once it is exhaustedStopIteration
How for worksfor x in items:calls iter(items) once, then next() until StopIteration
Generators and yieldcalling a function that contains yieldreturns a generator; the body has not run yet
Generator expressions[n * n for n in nums], (n * n for n in nums)builds the whole list, or computes one item at a time
Single-passsum(squares) a second time0
yield fromyield from [1, 2] inside a generatoryields 1, then 2
Large filesfor line in f:keeps one line in memory at a time
itertoolslist(islice(count(), 3))[0, 1, 2]
Async generatorsasync for page in fetch_pages():waits for each item from a slow source

How some other languages compare

TaskJS / TSJavaGo
Iteratefor...ofEnhanced forfor ... range
Signal the enddone: truehasNext() returns falseThe iterator function returns
Produce values on demandGenerator function*Stream runs on a terminal operationIterator function (1.23+)

Iterable and iterator

An iterable is an object that iter() can get an iterator from: a list, a string, a dict, a file. An iterator is what iter() returns; it keeps its place.

Shared data is orders = [101, 102] and cursor = iter(orders).

WriteMeaning
iter(orders)Get a fresh iterator from the list
next(cursor)Take the next order ID and advance the iterator
iter(cursor)Return the iterator itself
python
orders = [101, 102]
cursor = iter(orders)

print(iter(cursor) is cursor)
# prints: True
print(next(cursor))
# prints: 101
print(next(cursor))
# prints: 102
print(next(iter(orders)))
# prints: 101

cursor has gone through both order IDs. iter(orders) creates a fresh iterator, so the last call gets 101 again.

Iterator protocol

The iterator protocol defines how Python gets and uses an iterator. The method names below have two underscores on each end. They are dunder methods.

The parts of a countdown iterator

PartMeaning
class Countdown:Define a countdown type
__init__(self, start)Store the starting number when creating an object
__iter__(self)Return the iterator itself
__next__(self)Return one number and advance
raise StopIterationSignal that the iterator is exhausted
python
class Countdown:
    def __init__(self, start):
        self.remaining = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.remaining <= 0:
            raise StopIteration
        value = self.remaining
        self.remaining = self.remaining - 1
        return value


countdown = Countdown(2)
print(next(countdown))
# prints: 2
print(next(countdown))
# prints: 1
next(countdown)
# error: StopIteration

How for works

Shared data is orders = [101, 102].

PartMeaning
for order in orders:Get an iterator from orders and bind each value to order
next(cursor)Take one value from the iterator
except StopIteration:Catch the end-of-iteration signal and stop

A for loop calls iter() once. On each iteration it gets an item with next(). When that step raises StopIteration, the loop ends.

python
orders = [101, 102]
seen = []
for order in orders:
    seen.append(order)

print(seen)
# prints: [101, 102]

seen = []
cursor = iter(orders)
while True:
    try:
        order = next(cursor)
    except StopIteration:
        break
    seen.append(order)

print(seen)
# prints: [101, 102]

Generators and yield

The parts of yield step

PartMeaning
yieldHand out one value and suspend the function
stepThe value that next() receives
python
def count_steps():
    step = 1
    yield step
    step = step + 1
    yield step


steps = count_steps()
print(next(steps))
# prints: 1
print(next(steps))
# prints: 2

The first call suspends the function at yield step with step = 1. The second resumes it just after that point. The function kept the old value of step, so the increment gives 2. When the function finishes, the generator signals StopIteration.

List comprehensions and generator expressions

Read the syntax for producing squares

WriteMeaning
n * nThe value to compute for each n
for n in range(3)Bind n to 0, 1, then 2
[...]List comprehension, computes and stores the full list
(...)Generator expression, computes each value when requested
python
squares = [n * n for n in range(3)]
square_iter = (n * n for n in range(3))

print(squares)
# prints: [0, 1, 4]
print(next(square_iter))
# prints: 0
print(next(square_iter))
# prints: 1

Measure the size of both objects

Both expressions below describe the same 100,000 squares. The list holds all of them as soon as it is built. The generator keeps the state it needs to compute the next value.

python
import sys

squares = [n * n for n in range(100_000)]
square_iter = (n * n for n in range(100_000))

print(sys.getsizeof(squares))
# prints: 800984
print(sys.getsizeof(square_iter))
# prints: 208

A generator is single-pass

range(1, 4) gives the numbers from 1 up to 4, excluding 4. sum() takes all the remaining values and adds them up. Calling it again on the same exhausted generator gives 0, the sum of an empty sequence.

python
numbers = (n for n in range(1, 4))

print(sum(numbers))
# prints: 6
print(sum(numbers))
# prints: 0

numbers = (n for n in range(1, 4))
print(sum(numbers))
# prints: 6

yield from

Shared data is first_page = [101, 102].

PartMeaning
yield fromPass through each item from an iterable
first_pageThe source of the first set of items
python
def iter_orders():
    first_page = [101, 102]
    second_page = [103]
    yield from first_page
    yield from second_page


print(list(iter_orders()))
# prints: [101, 102, 103]

Read a large file line by line

Interview question: How do you read a 10 GB log file?

Open it with with and use for line in log. A text file is an iterator too. Each iteration gives one line. Filter or write out the result as you go.

PartMeaning
with ... as log:Bind the open file to log and close it when the block exits
for line in log:Take one line at a time from the file
encoding="utf-8"Select UTF-8 as the text encoding for reading or writing

The example creates a two-line file and prints the error line.

python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "orbit.log"
    path.write_text("INFO Orbit ready\nERROR Orbit timeout\n", encoding="utf-8")

    with path.open(encoding="utf-8") as log:
        for line in log:
            if line.startswith("ERROR "):
                print(line.rstrip("\n"))
                # prints: ERROR Orbit timeout

Standard library itertools

itertools comes with Python. The three functions below return iterators. Each example uses list() to display its small result.

FunctionUse it to
chainExhaust one input before moving on to the next
isliceSkip items and then take a slice
groupbyGroup adjacent items that have the same key

Join inputs with chain

chain(first_page, second_page) returns the items from each input in order. It can walk both inputs without building a combined list.

python
from itertools import chain

first_page = [101, 102]
second_page = [103]

print(list(chain(first_page, second_page)))
# prints: [101, 102, 103]

Take a slice with islice

islice(orders, 1, 3) takes items from position 1 up to, and excluding, 3. Positions start at 0. Skipped items are also consumed from the source iterator.

python
from itertools import islice

orders = iter([101, 102, 103, 104])
print(list(islice(orders, 1, 3)))
# prints: [102, 103]
print(next(orders))
# prints: 104

Group adjacent items with groupby

groupby() returns pairs of (key, group). for key, group in ... unpacks each pair into two names. The default key is the item itself, which is an order status in this example.

python
from itertools import groupby

statuses = ["paid", "refunded", "paid"]
print([key for key, group in groupby(statuses)])
# prints: ['paid', 'refunded', 'paid']

sorted_statuses = sorted(statuses)
print([(key, list(group)) for key, group in groupby(sorted_statuses)])
# prints: [('paid', ['paid', 'paid']), ('refunded', ['refunded'])]

The two "paid" values are separated, so the first pass creates two groups for that status. sorted() puts them together in a new list.

Async generators

An async def function with yield is an async generator. It produces items one at a time and can await while waiting for data, such as the next page of results from an API. The caller takes items with async for, inside an async function. asyncio.run(main()) runs an async function from ordinary code.

python
import asyncio


async def fetch_pages():
    for page in [[101, 102], [103]]:
        await asyncio.sleep(0)  # stands in for an API call that must be awaited
        yield page


async def main():
    async for page in fetch_pages():
        print(page)


asyncio.run(main())
# prints:
# [101, 102]
# [103]

Key takeaways

  • An iterable lets iter() get an iterator. An iterator keeps its place and returns items through next().
  • for gets the iterator once. A StopIteration while taking the next value ends the loop.
  • yield hands out a value and pauses. yield from passes along each value from another source.
  • A list comprehension builds the whole list at once. A generator expression computes each value when asked.
  • A generator runs through once. Read a large file with for line in log to handle one line at a time.
  • chain joins sources, islice takes a slice and groupby groups adjacent items with the same key.

Sources