Editor

Predict the takewhile Output

Intermediate · Predict the output · 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

What does this code print? Remember that takewhile stops at the FIRST item that fails the condition.

from itertools import takewhile
nums = [1, 3, 5, 2, 4, 7]
result = list(takewhile(lambda x: x < 5, nums))
print(result)
from itertools import takewhile
nums = [1, 3, 5, 2, 4, 7]
result = list(takewhile(lambda x: x < 5, nums))
print(result)

More itertools exercises

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