The itertools
module in the standard library provides a number of functions for working with iterables through iterators.
The takewhile()
function in the module takes an iterable and a predicate as arguments and returns those elements of the iterable, up to the point where the predicate evaluates to False
.
takewhile(predicate, iterable)
predicate |
Required. A function that takes a single argument and returns a boolean value. |
iterable |
An iterable objects such as list, set, range, tuple, etc |
The function returns an iterator which returns elements from the iterable as long as the predicate remains is True
. When predicate(element) evaluates to False, the iterator stops, any subsequent calls will result in a StopIteration
exception.
from itertools import takewhile
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#get elements until an element larger or equal five is encounterd
for i in takewhile(lambda x: x < 5, data):
print(i)
In the above example, the iterator returns an element from the list as long as the element is less than five. Once 5 or a greater value is encountered the iterator stops meaning that we cannot get any other element beyond there.
Example with strings
from itertools import takewhile
data = ['PYTHON', 'C++', 'RUBY', 'php', 'CSS', 'HTML']
result = list(takewhile(lambda x: x.isupper(), data))
print(result)
for i in result:
print(i)
In the above example, the iterator stops when a string in the list is encountered whose characters are not all uppercase('php').
The opposite of the takewhile()
is the dropwhile()
function which creates an iterator that doesn't return elements up until the specified predicate fails.