Phase 6 of 25 · Topic 6.5

itertools Module Masterclass (chain, islice, groupby, cycle)

1Concept

The `itertools` module provides high-speed C-implemented iterator building blocks: `chain` flattens iterables; `islice` slices iterators without indexing; `groupby` clusters consecutive identical keys; `product` computes Cartesian products.

2Architecture Diagram

itertools.chain([1, 2], [3, 4]) ---> Generates 1, 2, 3, 4 lazily without creating combined list

3Code Example

Python 3.12
from itertools import chain, islice, groupby

combined = list(chain(["A", "B"], ["C", "D"]))
print(f"Chained: {combined}")

sorted_data = [("Eng", "Alice"), ("Eng", "Bob"), ("Fin", "Charlie")]
print("=== GroupBy Results ===")
for dept, members in groupby(sorted_data, key=lambda x: x[0]):
    print(f"{dept}: {[m[1] for m in members]}")

first_three = list(islice(range(100), 3))
print(f"islice:  {first_three}")

4Expected Output

Chained: ['A', 'B', 'C', 'D']
=== GroupBy Results ===
Eng: ['Alice', 'Bob']
Fin: ['Charlie']
islice:  [0, 1, 2]

5Key Takeaways

  • `itertools.groupby()` requires data to be sorted by the key beforehand.
  • `islice()` works on infinite generators where standard list slicing `[start:stop]` fails.
  • Itertools operations run at native C speeds, vastly outperforming custom Python loops.