Efficient iteration patterns with Python's itertools
Python's itertools module supplies iterator building blocks for sequences, generators, file rows, and other iterables without constructing every possible result in memory. Its lazy pipeline model is especially useful for CSV exports, log files, database cursors, and API responses: the consumer requests another value, and the tool produces it on demand.
Efficiency here means both lower memory use and less repeated Python-level looping. The module also provides concise forms of grouping, pairing, cumulative calculations, and Cartesian products. It does not make expensive computations cheap, however: a product representing millions of outcomes still represents millions of outcomes. Bounding the work is as important as choosing the iterator.
Choosing the right iterator
The functions in itertools return iterator objects, so values normally arrive once and then the iterator is exhausted. For example, iter([1, 2]) creates a fresh iterator over the list, while iter(existing_generator) returns the same generator. This one-pass behaviour distinguishes these tools from list comprehensions, which store every result immediately.
| Iteration need | Useful itertools tools | Behaviour and caution |
|---|---|---|
| Traverse several sources | chain, chain.from_iterable |
Produces items lazily across one or more iterables |
| Limit or skip values | islice |
Avoids materialising a prefix, but skipping still traverses items |
| Combine aligned values | zip_longest |
Adds a fill value when streams have different lengths |
| Group adjacent records | groupby |
Groups consecutive keys only unless the data is sorted |
| Calculate running values | accumulate |
Supports totals, products, and custom functions |
| Generate alternatives | product, permutations, combinations |
Output grows rapidly as inputs or selection sizes increase |
Most operations still delegate their underlying work to Python objects. A C-backed iterator can remove several layers of explicit indexing, but it cannot avoid reading a source, hashing a key, or sorting a large collection. Use islice when only a prefix matters, chain.from_iterable to flatten several sources, and zip_longest when streams may have different lengths. The itertools practice exercises extend these ideas to common algorithm problems.
Building bounded-memory pipelines
A bounded pipeline keeps intermediate lists out of memory. The following function streams at most 500 records from a CSV file; closing the file when iteration finishes also releases its descriptor promptly.
import csv
from itertools import islice
def first_rows(path, limit=500):
with open(path, newline="", encoding="utf-8") as handle:
yield from islice(csv.DictReader(handle), limit)
The same pattern works across several sources. chain.from_iterable accepts a generator of iterables and yields their items in sequence, while islice can skip or stop lazily. Skipping still traverses the skipped elements, so it is not a random-access shortcut. takewhile stops at the first false condition, whereas filterfalse selects records that fail a predicate.
For running totals, accumulate applies a function to successive values, and its initial argument establishes a known baseline. starmap unpacks tuples into a function, and zip_longest inserts a fill value for exhausted inputs. Together, these primitives form readable transformations without repeatedly appending to temporary lists.
Exploring products and combinations
product forms a Cartesian product, permutations emits ordered arrangements, and combinations emits unordered selections. Each iterator yields results only as they are requested, although the number of possible results may be much larger than the original input.
from itertools import combinations, permutations, product
postcode_prefixes = ("2000", "3000", "4000", "5000")
courier_options = ("standard", "express")
plans = product(postcode_prefixes, courier_options)
crew = permutations(("collector", "packer", "driver"), 2)
vehicle_pairs = combinations(("compact", "standard", "electric"), 2)
The semantic differences matter when duplicate values are present. permutations and combinations treat positions as distinct, so repeated input values can produce repeated outputs. Use combinations_with_replacement when repeated selections are valid. The repeat argument on product also supports repeated factors, but it increases the output count exponentially.
For an Australian delivery-planning example, pairing postcode prefixes with courier options creates a manageable set of scenarios. Adding staff permutations or more service levels quickly multiplies that set. Keep the candidate space bounded, stop after the required number of results, or replace exhaustive generation with a targeted search when only the best arrangement is needed.
Grouping and transforming streams
groupby is convenient for adjacent records, but it does not gather matching keys that occur in separate parts of the stream. Its key function determines the grouping criterion, and the current group must be consumed before advancing to the next one.
from itertools import groupby
from operator import itemgetter
for state, group in groupby(rows, key=itemgetter("state")):
print(state, len(list(group)))
If records with the same state must be collected together regardless of their original positions, sort by the grouping key first. That convenience has a cost: sorting generally materialises the data and removes its original order. A dictionary can also support global grouping, provided its memory usage remains appropriate for the dataset.
tee creates two independent iterators over one source and buffers items needed by the slower consumer. It is useful for comparing streams, but substantial divergence between the branches can increase memory usage. cycle repeats a sequence indefinitely and caches its items, so it should not wrap an unbounded source. When the objective is to optimise a sequence rather than enumerate candidates, a dynamic programming example demonstrates a different algorithmic approach.
Practical recipes for Australian data work
Python appears throughout Australia's software, data, and fintech market, from Sydney and Melbourne engineering teams to Brisbane and Perth analysis roles. Local inputs add further requirements: the ASX trading calendar and Australian Eastern Time affect schedules, while workplace shorthand such as arvo, barbie, and servo may appear in text fields. Reliable pipelines address these requirements with a small set of reusable patterns:
- Batch records without flattening them: use
itertools.batchedon Python 3.12 and later, or an equivalentislicerecipe on earlier versions, to process fixed groups while retaining streaming behaviour. - Join sources safely: use
chain.from_iterablefor pages, files, or API batches, and wrap each source withislicewhen it has a known limit. - Calculate running metrics: use
accumulatefor totals and custom moving calculations instead of maintaining a separate output list. - Align unequal streams: use
zip_longestwith an explicit fill value so that missing fields remain visible rather than being silently discarded. - Produce constrained alternatives: choose
product,permutations, orcombinationsaccording to whether order matters, then cap the number of generated results.
Reliability checks belong beside these recipes:
- Bound combinatorial output: record an expected result count before iterating, and fail early if a product or permutation set becomes unexpectedly large.
- Sort only when global grouping is required: account for the extra memory and lost input order introduced by sorting records for
groupby. - Budget iterator caches: treat
teebuffers and the items retained bycycleas additional memory held outside the original dataset. - Test edge cases explicitly: include empty sources, single records, missing fields, duplicate keys, and Unicode text from Australian names and addresses.
- Centralise local terminology: map shorthand such as barbie and servo in one lookup rather than scattering special cases through transformation functions.
- Model business schedules correctly: account for weekends, ASX holidays, and Australian Eastern Time instead of assuming every weekday is interchangeable.
The result is a pipeline in which each stage has one clear responsibility, intermediate data remains bounded, and iteration follows the shape of the source rather than forcing every record into memory at once.