Editor

Group Numbers as Even or Odd

Advanced · Write the code · 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

Given numbers = [1, 3, 2, 4, 5, 7, 6, 8], sort them by whether they're even or odd, then use groupby to print each group. Use lambda x: x % 2 == 0 as the key. Print in the format:

False: [1, 3, 5, 7]

True: [2, 4, 6, 8]

from itertools import groupby
numbers = [1, 3, 2, 4, 5, 7, 6, 8]
# Sort by even/odd, then group and print

More itertools exercises

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