CodeBlanks Logo Icon CodeBlanks

groupby

Learn grouping with groupby.

groupby

groupby(iterable, key=fn) groups consecutive items with the same key in an iterable. Each group is returned as a (key, group_iterator) pair.

Important: groupby only groups consecutive same keys. The data must be sorted by key beforehand; otherwise the same key can appear in multiple groups. If key is not given, the items themselves are the keys.

The group iterator exhausts

The group g returned from groupby is an iterator. Once you walk it, it exhausts; walking again returns nothing. So a common practice is to convert the group to a list immediately with list(g).

Example: for k, g in groupby([1, 1, 2]):\n print(k, list(g)). This code prints the key and the items as a list for each group. If you want to use the group iterator more than once, convert it to a list and store it.

Practice Count groups with groupby

Start with from itertools import groupby. Write the loop for k, g in groupby([1, 1, 2, 2, 3]):. In the body print each group's key and count with print(k, len(list(g))).

Starter code

main.py
# Count groups with groupby

Sample solution

main.py
# Count groups with groupby
from itertools import groupby

for k, g in groupby([1, 1, 2, 2, 3]):
    print(k, len(list(g)))

Expected output

1 2
2 2
3 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does groupby expect the data to be?

  • Random order
  • Reverse sorted
  • Sorted by key Correct answer
  • Unsorted

Explanation: groupby expects the data to be sorted by key.

2 groupby loop

Question
from itertools import groupby

for k, g in ____([1, 1, 2, 2, 3]):
    print(k, len(list(g)))
Answer
from itertools import groupby

for k, g in groupby([1, 1, 2, 2, 3]):
    print(k, len(list(g)))

Explanation: groupby creates consecutive groups.

3 Match the groupby parts

Term Meaning
groupby Grouping function
key Key function
(k, g) Key and group
list(g) Convert to list

All lessons in Intermediate