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.
On this page (16)
- Iterators and generators
- Iterable and iterator
- Iterator protocol
- How for works
- Generators and yield
- List comprehensions and generator expressions
- A generator is single-pass
- yield from
- Read a large file line by line
- Standard library itertools
- Join inputs with chain
- Take a slice with islice
- Group adjacent items with groupby
- Async generators
- Key takeaways
- Sources
Iterators and generators
What does this code print?
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,listandforall ask for one item at a time withnext()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:
| Section | Example | Result |
|---|---|---|
| Iterable and iterator | it = iter([1, 2]), then next(it) | 1 |
| Iterator protocol | next(it) once it is exhausted | StopIteration |
How for works | for x in items: | calls iter(items) once, then next() until StopIteration |
Generators and yield | calling a function that contains yield | returns 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-pass | sum(squares) a second time | 0 |
yield from | yield from [1, 2] inside a generator | yields 1, then 2 |
| Large files | for line in f: | keeps one line in memory at a time |
itertools | list(islice(count(), 3)) | [0, 1, 2] |
| Async generators | async for page in fetch_pages(): | waits for each item from a slow source |
How some other languages compare
| Task | JS / TS | Java | Go |
|---|---|---|---|
| Iterate | for...of | Enhanced for | for ... range |
| Signal the end | done: true | hasNext() returns false | The iterator function returns |
| Produce values on demand | Generator function* | Stream runs on a terminal operation | Iterator 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).
| Write | Meaning |
|---|---|
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 |
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
| Part | Meaning |
|---|---|
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 StopIteration | Signal that the iterator is exhausted |
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].
| Part | Meaning |
|---|---|
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.
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
| Part | Meaning |
|---|---|
yield | Hand out one value and suspend the function |
step | The value that next() receives |
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
| Write | Meaning |
|---|---|
n * n | The 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 |
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.
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.
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].
| Part | Meaning |
|---|---|
yield from | Pass through each item from an iterable |
first_page | The source of the first set of items |
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.
| Part | Meaning |
|---|---|
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.
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.
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.
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.
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.
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.
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 throughnext(). forgets the iterator once. AStopIterationwhile taking the next value ends the loop.yieldhands out a value and pauses.yield frompasses 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 logto handle one line at a time. chainjoins sources,islicetakes a slice andgroupbygroups adjacent items with the same key.
Sources
- The iterator protocol and generator functions. Python 3.11 Tutorial (opens in a new tab)
- Generator expressions,
yield fromand async generators. Python 3.11 Expression Reference (opens in a new tab) - Measuring object size.
sys.getsizeof(opens in a new tab) - Reading files and creating temporary directories. Python I/O (opens in a new tab),
tempfile(opens in a new tab) - Joining, slicing and grouping.
itertools(opens in a new tab) - Iteration in other languages. MDN (opens in a new tab), Java enhanced for (opens in a new tab), Java Stream (opens in a new tab), Go range (opens in a new tab)
- Every example was run with
python3(Python 3.11.9).
