The Python itertools.dropwhile() function is used to drop elements from an iterable as long as a specified condition is True. Once the condition becomes False, the function returns the remaining elements without checking further.
This function is useful when you want to ignore leading elements that satisfy a condition and process the rest of the iterable.
SyntaxFollowing is the syntax of the Python itertools.dropwhile() function −
itertools.dropwhile(predicate, iterable)Parameters
This function accepts the following parameters −
This function returns an iterator that provides elements from iterable, starting from the first element for which predicate returns False.
Example 1Following is an example of the Python itertools.dropwhile() function. Here, we drop numbers from the list while they are less than 5 −
import itertools def condition(x): return x < 5 data = [1, 2, 3, 5, 6, 7] result = itertools.dropwhile(condition, data) for num in result: print(num)
Following is the output of the above code −
5 6 7Example 2
Here, we use itertools.dropwhile() function to ignore initial words starting with a lowercase letter −
import itertools def starts_with_lower(s): return s[0].islower() words = ["apple", "banana", "Cherry", "Date", "Elderberry"] filtered_words = itertools.dropwhile(starts_with_lower, words) for word in filtered_words: print(word)
Output of the above code is as follows −
Cherry Date ElderberryExample 3
Now, we use itertools.dropwhile() function with a list of tuples, dropping tuples where the first element is negative −
import itertools def is_negative(t): return t[0] < 0 data = [(-2, "A"), (-1, "B"), (0, "C"), (1, "D"), (2, "E")] result = itertools.dropwhile(is_negative, data) for item in result: print(item)
The result obtained is as shown below −
(0, "C") (1, "D") (2, "E")Example 4
We can use itertools.dropwhile() function with numerical data, dropping elements while they are even −
import itertools def is_even(n): return n % 2 == 0 numbers = [2, 4, 6, 7, 8, 10, 11] filtered_numbers = itertools.dropwhile(is_even, numbers) for num in filtered_numbers: print(num)
The result produced is as follows −
7 8 10 11
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4