← Back to Python, page 3

python-0042 · Medium mid

Which itertools functions come up most in interviews? Show groupby, chain, islice and combinations.

chain joins iterables, islice slices any iterator lazily, groupby groups consecutive items with the same key (so sort first), and combinations and permutations generate selections. accumulate gives running totals and pairwise gives neighbouring pairs. They are lazy and memory-efficient.

Full answer
python
from itertools import chain, islice, groupby, combinations, accumulate, pairwise, count
print(list(chain([1, 2], (3,), "ab")))
print(list(islice(count(10, 5), 4)))
sales = [("Pune", 3), ("Leeds", 5), ("Pune", 2)]
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sales, key=lambda s: s[0])])
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sorted(sales), key=lambda s: s[0])])
print(list(combinations("ABC", 2)))
print(list(accumulate([3, 1, 4])), list(pairwise([1, 3, 6])))

Output:

text
[1, 2, 3, 'a', 'b']
[10, 15, 20, 25]
[('Pune', 3), ('Leeds', 5), ('Pune', 2)]
[('Leeds', 5), ('Pune', 5)]
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[3, 4, 8] [(1, 3), (3, 6)]

The first groupby shows the classic mistake: unsorted data produces two separate 'Pune' groups because only consecutive items are grouped. Sorting first gives one group per city. islice takes four values from the infinite count without building anything large. combinations('ABC', 2) yields the three unordered pairs. accumulate gives running totals and pairwise (Python 3.10+) yields neighbouring pairs, useful for differences between readings.

python
from itertools import chain, islice, groupby, combinations, accumulate, pairwise, count
print(list(chain([1, 2], (3,), "ab")))
print(list(islice(count(10, 5), 4)))
sales = [("Pune", 3), ("Leeds", 5), ("Pune", 2)]
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sales, key=lambda s: s[0])])
print([(city, sum(n for _, n in grp)) for city, grp in groupby(sorted(sales), key=lambda s: s[0])])
print(list(combinations("ABC", 2)))
print(list(accumulate([3, 1, 4])), list(pairwise([1, 3, 6])))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • chain concatenates iterables
  • islice slices lazily
  • groupby needs sorted input
  • combinations and permutations generate selections
  • accumulate and pairwise for running values

Common mistakes

  • Using groupby on unsorted data
  • Materialising infinite iterators

Follow-ups

  • How would you batch an iterator into chunks?
  • What does itertools.product do?

Tips

  • Sort before groupby