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.
Python code
19 linesdef 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
[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
- Use itertools.takewhile(predicate, iterable) from the standard library for the same logic without a custom function
- 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
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.