Python’s itertools module provides a robust set of tools for working with iterators. One of the lesser-known but convenient functions is itertools.dropwhile(). It allows you to skip elements in an iterable as long as a specific condition remains true — and once the condition fails, it yields the rest of the elements unchanged.
The function syntax is simple:
itertools.dropwhile(predicate, iterable)
predicate — a function that returns True or False
iterable — any iterable object (list, tuple, generator, etc.)
dropwhile() keeps dropping (skipping) items while the predicate returns True.
As soon as the predicate returns False for the first time, the rest of the items are yielded without further testing.
|
1 2 3 4 5 |
import itertools max_value = 99.00 values = [95, 97, 94, 96, 100, 102, 98] values_after_max = list(itertools.dropwhile(lambda value: value <= max_value, values)) print(values_after_max) |
output:
|
1 |
[100, 102, 98] |
Here’s what happens step-by-step:
-
The lambda function checks whether each
value <= 99.00. -
For
95, 97, 94, 96→ condition is True, sodropwhilekeeps dropping them. -
When it reaches
100, the condition becomes False. -
From that point onward, it stops checking and returns all remaining elements:
[100, 102, 98].
Last Updated on 2025-11-04 by gantovnik
Recent Comments