itertools.groupby, chain & islice

Iteration recipes

Lesson 8 of 20 · 11 min · Module 2: Work with data efficiently

The itertools module contains small building blocks for loops. Three of them solve problems you meet constantly: grouping runs, joining sequences, and taking a slice of a stream.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Group consecutive items with groupby
  • Combine iterables with chain
  • Take part of a stream with islice

The idea

groupby(items) groups consecutive equal items, yielding (key, group) pairs. chain(a, b) iterates over several iterables as one. islice(items, n) takes the first n items of any iterable, even an endless one.

from itertools import groupby, chain, islice, count
print([(k, len(list(g))) for k, g in groupby("aaabcc")])
print(list(chain([1, 2], [3])))
print(list(islice(count(10), 3)))

01groupby only joins neighbours

groupby("aabaa") produces a, b, a: the last two a characters are a new group because b interrupted them. That is exactly what run-length encoding needs. To group all equal items, sort first.

from itertools import groupby
print([k for k, g in groupby("aabaa")])
Output
['a', 'b', 'a']

02Consume each group once

Each group is a lazy iterator tied to the main loop. Use it (for example with list or len(list(...))) before moving to the next key.

03islice makes infinite streams safe

itertools.count() never ends, so list(count()) would run forever. islice(count(), 4) stops after four items. Lazy pipelines like this process huge data without loading it all.

Your turn

Write compress(text) that performs run-length encoding: "aaabcc" becomes "a3b1c2". Write first_unique(*sequences, n) (n is keyword-only) that returns the first n distinct items found across all sequences, in order.

What the checks look for

  • Compresses runs of characters
  • Counts runs, not totals
  • Finds the first distinct items across sequences
  • Stops early and works with an endless iterator
Try it in the editor →

Take this with you

itertools gives you tested building blocks for grouping, joining, and slicing streams.

Go a little further

Write decompress(text) that turns "a3b1c2" back into "aaabcc", supporting counts above 9.

Learn Python Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →