How to Implement takewhile Generator in Python

A generator that yields items from an iterable until a condition fails, like itertools.takewhile.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

10 lines
Python 3.9+
def takewhile(predicate, iterable):
    for item in iterable:
        if not predicate(item):
            break
        yield item

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 1, 2, 3]
    result = list(takewhile(lambda x: x < 4, numbers))
    print(result)

Output

stdout
[1, 2, 3]

How it works

This generator loops through the iterable one item at a time, calling predicate(item) on each. The moment predicate returns False, the loop breaks and the generator stops. Because it is a generator function, values are produced lazily — no full list is created until you consume it, like with list(). This mimics the standard library itertools.takewhile, which is useful when you want the same behavior without importing an external module.

Common mistakes

  • Forgetting that the generator stops permanently once the condition fails; it does not resume after a later matching item.
  • Treating the generator as if it returns a list; you must call `list()` or iterate to get the values.
  • Passing a predicate that raises an exception for early items, causing the break to trigger unexpectedly.

Variations

  1. Use `itertools.takewhile(predicate, iterable)` from the standard library for a built-in implementation.
  2. Use a list comprehension with a break-like structure if you are fine with eager evaluation and a bounded input.

Real-world use cases

  • Reading log lines from a file and stopping once you hit a line starting with 'ERROR' to get prefix context.
  • Processing a stream of sensor readings and collecting values until a threshold is exceeded, then halting.
  • Parsing a configuration file where you want to capture all lines until a 'section end' marker appears.

Sponsored

Run this sample

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

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.