itertools.takewhile enables you to take items from a sequence until a condition first becomes False
.
def is_even(x):
return x % 2 == 0
lst = [0, 2, 4, 12, 18, 13, 14, 22, 23, 44]
result = list(itertools.takewhile(is_even, lst))
print(result)
This outputs [0, 2, 4, 12, 18]
.
Note that, the first number that violates the predicate (i.e.: the function returning a Boolean value) is_even
is, 13
.
Once takewhile
encounters a value that produces False
for the given predicate, it breaks out.
The output produced by takewhile
is similar to the output generated from the code below.
def takewhile(predicate, iterable):
for x in iterable:
if predicate(x):
yield x
else:
break
Note: The concatenation of results produced by takewhile
and dropwhile
produces the original iterable.
result = list(itertools.takewhile(is_even, lst)) + list(itertools.dropwhile(is_even, lst))