Skip to content

Iteration and generators

Many tasks are loops over events in order: compare each payment with the previous one, send rows in chunks, group neighbours by key. The standard library turns each of these into one line. Generators add one more thing: the loop keeps working when the input is too large for memory, which is the usual follow-up question.

The gap between consecutive payments is a classic: renewals that came late, sessions with a pause, events out of order. Pair each item with the next one:

from datetime import date
from itertools import pairwise
renewals = [date(2026, 6, 3), date(2026, 7, 3), date(2026, 8, 3), date(2026, 9, 14)]
print([(b - a).days for a, b in zip(renewals, renewals[1:])])
print([(b - a).days for a, b in pairwise(renewals)])
for n, (a, b) in enumerate(pairwise(renewals), start=2):
if (b - a).days > 35:
print(f"payment {n} came {(b - a).days} days after the previous one")
[30, 31, 42]
[30, 31, 42]
payment 4 came 42 days after the previous one
  • zip(xs, xs[1:]) works everywhere but copies the list. pairwise (Python 3.10+) works on any iterable, a generator included, and copies nothing.
  • enumerate(..., start=2) numbers the second item of each pair, so the message shows the number a person would count. Use enumerate instead of range(len(xs)).
  • Both versions need the input sorted by time. Sort first if the task does not promise it.

zip has a quiet trap: it stops at the shortest input.

products = ["prd_01", "prd_02", "prd_03"]
revenue = ["114.93", "88.92"]
print(list(zip(products, revenue)))
print(list(zip(products, revenue, strict=True)))
[('prd_01', '114.93'), ('prd_02', '88.92')]
Traceback (most recent call last):
...
ValueError: zip() argument 2 is shorter than argument 1

prd_03 disappeared without an error. When two lists must have the same length, pass strict=True (Python 3.10+).

Inserts, API calls and messages often go in chunks: 500 rows per INSERT, 100 ids per request. For a list, a range with step n and slices is enough, and the drill below asks for it. For anything else, there are two tools:

from itertools import batched, islice
ids = ["t1", "t2", "t3", "t4", "t5"]
print(list(batched(ids, 2)))
def chunks(iterable, n):
it = iter(iterable)
while batch := list(islice(it, n)):
yield batch
print(list(chunks(ids, 2)))
print(list(chunks((f"t{i}" for i in range(1, 6)), 2)))
[('t1', 't2'), ('t3', 't4'), ('t5',)]
[['t1', 't2'], ['t3', 't4'], ['t5']]
[['t1', 't2'], ['t3', 't4'], ['t5']]
  • itertools.batched (Python 3.12+) returns tuples, works on any iterable, and raises ValueError: n must be at least one for n = 0. Python 3.13 adds strict=True, which raises if the last batch is short.
  • chunks does the same in older versions. islice takes up to n items from the same iterator each time, so it also works on a generator, as the third line shows.
  • With n = 0, chunks silently returns nothing. Check n first and raise ValueError, as the drill does.

A list holds every item at once. A generator produces the next item only when the loop asks for it:

import sys
squares_list = [i * i for i in range(1_000_000)]
squares_gen = (i * i for i in range(1_000_000))
print(sys.getsizeof(squares_list), sys.getsizeof(squares_gen))
print(sum(squares_gen), sum(squares_gen))
8448728 200
333332833333500000 0

The list’s array alone takes 8.4 MB (the numbers themselves take more). The generator takes 200 bytes, whatever the length. The second line shows the price: a generator runs only once. The second sum gets nothing and returns 0. len() does not work on it either.

A function with yield is a generator too. This is the usual shape for a file that does not fit in memory: read a line, parse it, pass it on, keep only the totals:

import io
from collections import defaultdict
from decimal import Decimal
f = io.StringIO("cus_01,9.99\ncus_02,4.99\ncus_01,0.01\n\ncus_03,49.99\n") # stands for open("payments.csv")
def read_payments(lines):
for line in lines: # a file object yields one line at a time
line = line.strip()
if not line:
continue
customer_id, amount = line.split(",")
yield customer_id, Decimal(amount)
totals = defaultdict(Decimal)
for customer_id, amount in read_payments(f):
totals[customer_id] += amount
print(dict(totals))
{'cus_01': Decimal('10.00'), 'cus_02': Decimal('4.99'), 'cus_03': Decimal('49.99')}

Memory now depends on the number of customers, not on the number of lines. Parsing and summing stay separate, so each part is easy to test with a short list instead of a file. next(gen) takes one item by hand, which helps when you debug.

TalkSay it out loud

The input file has 50 million lines and does not fit in memory. What changes in your code?

Say your answer out loud first, then open it.

Show the answer

“I process it as a stream: iterate over the file line by line or use a generator with yield, and keep only the aggregates — a dict of totals, not the rows. If I need grouping by a key with many values, I push the work to the database or process it in chunks.”

Add the cost: one pass, O(n) time, memory O(k) for k keys. If even the totals do not fit, the data belongs in the database (see Python and SQL).

itertools.groupby starts a new group every time the key changes. It does not look back, so equal keys that are not neighbours land in different groups:

from itertools import groupby
from operator import itemgetter
rows = [("north_market", 8), ("south_market", 9), ("north_market", 3), ("web", 4)]
print([(channel, len(list(g))) for channel, g in groupby(rows, key=itemgetter(0))])
rows.sort(key=itemgetter(0))
print([(channel, sum(n for _, n in g)) for channel, g in groupby(rows, key=itemgetter(0))])
[('north_market', 1), ('south_market', 1), ('north_market', 1), ('web', 1)]
[('north_market', 11), ('south_market', 9), ('web', 4)]

north_market appears twice in the first result, and no error warns you. Sort by the same key first: that costs O(n log n). A defaultdict needs no sorting and is O(n), so it is the usual choice (see dict and Counter). groupby fits when the input is already sorted, for example rows from SQL with ORDER BY, and you want to handle one group at a time without keeping the others.

from itertools import accumulate, chain, islice, count
from decimal import Decimal
daily = [Decimal("10.00"), Decimal("4.99"), Decimal("0.01")]
print(list(accumulate(daily))) # running total
print(list(chain.from_iterable([["prd_01"], ["prd_02", "prd_03"]]))) # flatten one level
print(list(islice(count(1), 3))) # first 3 of an endless iterator
[Decimal('10.00'), Decimal('14.99'), Decimal('15.00')]
['prd_01', 'prd_02', 'prd_03']
[1, 2, 3]

Not sure what else the module has? dir(itertools) lists every function, and the end of its documentation page has recipes (see Testing and complexity).

PythonWrite a function

Split a list into batches of n (the last one may be shorter) — e.g. to insert rows into the database in chunks. Return a list of lists. n must be positive: raise ValueError otherwise.

Data and an example

Example: batches([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]

4 checks. Your own print() output is shown too.

def batches(items, n):
    ...
Show answer

Reference

def batches(items, n):
if n <= 0:
raise ValueError("n must be positive")
return [items[i:i + n] for i in range(0, len(items), n)]

Checks and the expected values

  • batches([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]
  • batches([], 3) → []
  • batches([1], 0) → raises ValueError
  • batches([1, 2], -1) → raises ValueError

A range with step n and a slice for each start. For a stream that does not fit in memory, use a generator with yield or itertools.batched (Python 3.12+). batched gives tuples, and the task asks for lists: [list(b) for b in batched(items, n)]. n <= 0 is an error, not an endless loop, so check it first and raise ValueError.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.