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 lessonWhat 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
- Flatten a Nested ListBeginner
- Generate All Coin Flip OutcomesIntermediate
- Find All 2-Letter PermutationsIntermediate
- Compute a Running TotalBeginner
- Group Numbers as Even or OddAdvanced
- Fix the groupby BugAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz