Take While Predicate True From Start in Python

Create a custom take_while function that collects elements from an iterable until a predicate returns False, then stops.

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

Python code

19 lines
Python 3.9+
def take_while(predicate, iterable):
    """Return elements from iterable until the predicate becomes False."""
    result = []
    for item in iterable:
        if predicate(item):
            result.append(item)
        else:
            break
    return result


if __name__ == "__main__":
    numbers = [2, 4, 6, 7, 8, 10, 11]
    is_even = lambda x: x % 2 == 0
    print(take_while(is_even, numbers))  # [2, 4, 6]

    text = "abc123def"
    is_alpha = lambda ch: ch.isalpha()
    print(take_while(is_alpha, text))  # ['a', 'b', 'c']

Output

stdout
[2, 4, 6]
['a', 'b', 'c']

How it works

This implementation iterates through the iterable and appends each item to a result list as long as the predicate returns True. When the predicate returns False for the first time, the loop breaks immediately, stopping further processing. This behavior matches the functional programming pattern of taking elements from the beginning while a condition holds. The function works with any iterable, including lists and strings, and returns a list of collected items.

Common mistakes

  • Not breaking out of the loop after the predicate returns False, causing extra iterations
  • Attempting to modify the iterable while iterating over it
  • Forgetting that the function stops at the first False, not collecting later True elements

Variations

  1. Use itertools.takewhile(predicate, iterable) from the standard library for the same logic without a custom function
  2. Convert to a generator with yield to avoid building a full list when streaming large data

Real-world use cases

  • Truncating log lines that start with a header format until the first data marker appears.
  • Parsing command output to capture initial configuration lines that match a prefix pattern.
  • Streaming sensor readings until the first anomalous reading, then stopping data collection.

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.