Python Language Itertools Module itertools.takewhile

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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))


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

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))

Got any Python Language Question?