On this page
  1. itertools
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Grouping Consecutive Records with groupby()
  7. 2. Windowing & Lazy Slicing (pairwise, islice)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

itertools

Prev: ipaddress | Up: stdlib_module | Next: json
Rel: functools, operator
Ref: docs.python.org — itertools
Tags: #public #python3 #stdlib


Import

import itertools

Overview

Memory-efficient, C-speed lazy iterator building blocks for slicing, chaining, grouping, batching, and combinatorics. Use itertools whenever you process large streams or pipelines without materializing intermediate lists in memory.

Quick Start

import itertools

flat = list(itertools.chain.from_iterable([[1, 2], [3, 4], [5]]))
assert flat == [1, 2, 3, 4, 5]

batches = list(itertools.batched(range(7), 3))
assert batches == [(0, 1, 2), (3, 4, 5), (6,)]

Implementation Walkthrough

1. Grouping Consecutive Records with groupby()

groupby() only groups adjacent items with the same key—always sort by the same key function first unless the input is already clustered:

import itertools

rows = [
    {"dept": "eng", "name": "Ada"},
    {"dept": "ops", "name": "Lin"},
    {"dept": "eng", "name": "Grace"},
]
rows_sorted = sorted(rows, key=lambda r: r["dept"])
by_dept = {
    dept: [r["name"] for r in group]
    for dept, group in itertools.groupby(rows_sorted, key=lambda r: r["dept"])
}
assert by_dept == {"eng": ["Ada", "Grace"], "ops": ["Lin"]}

2. Windowing & Lazy Slicing (pairwise, islice)

import itertools

temps = [68, 70, 74, 71]
deltas = [b - a for a, b in itertools.pairwise(temps)]
assert deltas == [2, 4, -3]

first_three = list(itertools.islice(itertools.count(10, 5), 3))
assert first_three == [10, 15, 20]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes