Editor

Fix the groupby Bug

Advanced · Fix the bug · from Python itertools: Powerful Tools for Working with Iterables

From the lesson: Python itertools: Powerful Tools for Working with Iterables

Imagine you have a Swiss Army knife for loops. Instead of writing complicated nested loops and temporary lists, you pull out the right tiny tool and the job is done in one clean line.

Read the lesson

This code tries to group words by first letter, but the output is wrong because the data isn't sorted. Fix the code so it correctly groups all words by their first letter.

Expected output:

a: ['ant', 'ape']

b: ['bat', 'bee']

c: ['cat', 'cow']

from itertools import groupby
words = ['cat', 'ant', 'bat', 'ape', 'cow', 'bee']
# Bug: data not sorted before groupby!
for letter, group in groupby(words, key=lambda w: w[0]):
print(f'{letter}: {list(group)}')

More itertools exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz