Published October 13, 2025
Python has a ton of tools in its standard library for working with collections of data. The biggest set is probably found
in the itertools module. Today (OK - it was last week but I had already published a
TIL that day and it's taken me a bit to get around to writing
this.) I learned about itertools.dropwhile. This handy little function will give you an iterable starting at the first
value of the supplied iterable that does not meet the required criteria. The criteria are supplied in the form of a function
that returns a bool so it would return the iterable starting at the first entry that returns False.
Let's look at an example. Let's say I have a list of numbers that includes both positive and negative integers:
values = [4, 3, -6, 2,-8, -5]
and let's say I want to filter out just the positive numbers at the start of the list:
def is_positive(n: int) -> bool:
return n > 0
I could write a function to do that:
def skip_first_positives(vals: list) -> list:
filtered = list()
vi = iter(vals)
try:
while n := next(vi):
if is_positive(n):
continue
filtered.append(n)
break
except StopIteration:
return filtered
filtered.extend(vi)
return filtered
skip_first_positives(values)
[-6, 2, -8, -5]
OR I could use itertools.dropwhile:
list(itertools.dropwhile(is_positive, values))
[-6, 2, -8, -5]
Another use case (and possibly a more useful one) is to drop leading 0s from a numeric string:
leading_zeroes = f'{'0' * 23}8787435321'
print(leading_zeroes)
000000000000000000000008787435321
print(''.join(itertools.dropwhile(lambda c: c == '0', leading_zeroes)))
8787435321
Thinking back over some of the code I've written, this would have come in handy more than once.