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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

13 lines
Python 3.9+
def 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

stdout
[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

  1. Use `itertools.dropwhile(predicate, iterable)` from the standard library for the same behavior
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.