Python Language itertools.dropwhile


itertools.dropwhile enables you to take items from a sequence after 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.dropwhile(is_even, lst))


This outputs [13, 14, 22, 23, 44].

(This example is same as the example for takewhile but using dropwhile.)

Note that, the first number that violates the predicate (i.e.: the function returning a Boolean value) is_even is, 13. All the elements before that, are discarded.

The output produced by dropwhile is similar to the output generated from the code below.

def dropwhile(predicate, iterable):
    iterable = iter(iterable)
    for x in iterable:
        if not predicate(x):
            yield x
    for x in iterable:
        yield x

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