Drop Elements From Start While Condition Is True in Python
This generator function drops elements from the beginning of an iterable while a predicate returns true, then yields the rest.
Python code
13 linesdef drop_while(predicate, iterable):
"""Drop elements from the start while predicate is true."""
it = iter(iterable)
for item in it:
if not predicate(item):
yield item
break
yield from it
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 1, 2, 5]
result = list(drop_while(lambda x: x < 3, numbers))
print(result) # [3, 4, 1, 2, 5]
Output
[3, 4, 1, 2, 5]
How it works
drop_while iterates through the input, skipping items while predicate(item) is true. Once it finds the first false value, it yields that item and then uses yield from to pass through the remaining elements. Aliasing with it = iter(iterable) ensures the same iterator is reused, so the loop and yield from do not restart the stream. This is equivalent to the itertools.dropwhile pattern, with a subtle difference: here the predicate is only called on the first false item, not on items after the drop phase.
Common mistakes
- Forgetting to call `iter()` and then passing the original iterable to `yield from` instead of the iterator
- Calling `predicate` on every item instead of stopping after the first false value
- Not handling empty iterables gracefully—the generator just produces nothing, which is correct
- Confusing this with `filter`, which removes matching items everywhere, not just from the start
Variations
- Use `itertools.dropwhile(predicate, iterable)` from the standard library for the same behavior
- Convert to a list comprehension with `next((i for i, x in enumerate(iterable) if not predicate(x)), len(iterable))` and slicing
Real-world use cases
- Skipping header or metadata lines in a log file that start with a comment marker until actual data begins.
- Trimming leading whitespace or filler tokens from a stream of user input before processing the real payload.
- Dropping leading null or placeholder entries from a time-series dataset that precede the first valid measurement.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.