Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.dropwhile() Function



The Pythonitertools.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.

Syntax

Following is the syntax of the Python itertools.dropwhile() function −

itertools.dropwhile(predicate, iterable)

Parameters

This function accepts the following parameters −

  • predicate: A function that returns True or False. Elements are dropped while the function returns True.
  • iterable: The iterable to be processed.

Return Value

This function returns an iterator that provides elements fromiterable, starting from the first element for whichpredicate returns False.

Example 1

Following is an example of the Python itertools.dropwhile() function. Here, we drop numbers from the list while they are less than 5 −

import itertoolsdef condition(x):   return x < 5data = [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 −

567

Example 2

Here, we use itertools.dropwhile() function to ignore initial words starting with a lowercase letter −

import itertoolsdef 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 −

CherryDateElderberry

Example 3

Now, we use itertools.dropwhile() function with a list of tuples, dropping tuples where the first element is negative −

import itertoolsdef is_negative(t):   return t[0] < 0data = [(-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 itertoolsdef is_even(n):   return n % 2 == 0numbers = [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 −

781011
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp