Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.takewhile() Function



The Pythonitertools.takewhile() function is used to return elements from an iterable as long as a specified condition remains true. Once the condition evaluates to false, iteration stops immediately.

This function is useful for processing sequences where elements should only be included until a certain threshold is met.

Syntax

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

itertools.takewhile(predicate, iterable)

Parameters

This function accepts the following parameters −

  • predicate: A function that returns True or False for each element.
  • iterable: The input iterable whose elements will be processed.

Return Value

This function returns an iterator that yields elements from the iterable until the predicate function returns False.

Example 1

Following is an example of the Python itertools.takewhile() function. Here, we take numbers from a list until we reach a number greater than or equal to 10 −

import itertoolsnumbers = [1, 4, 7, 9, 10, 12, 15]result = itertools.takewhile(lambda x: x < 10, numbers)for num in result:   print(num)

Following is the output of the above code −

1479

Example 2

Here, we use itertools.takewhile() function to extract elements from a sorted list of temperatures until a temperature of 30 or higher is encountered −

import itertoolstemperatures = [22, 24, 27, 29, 30, 32, 35]result = itertools.takewhile(lambda t: t < 30, temperatures)for temp in result:   print(temp)

Output of the above code is as follows −

22242729

Example 3

Now, we use itertools.takewhile() function to process a list of words, stopping when a word longer than 5 characters is encountered −

import itertoolswords = ["apple", "pear", "fig", "banana", "cherry", "grape"]result = itertools.takewhile(lambda w: len(w) <= 5, words)for word in result:   print(word)

The result obtained is as shown below −

applepearfig

Example 4

We can use itertools.takewhile() function to filter stock prices until a significant drop occurs −

import itertoolsstock_prices = [100, 105, 110, 115, 90, 80, 70]result = itertools.takewhile(lambda price: price > 95, stock_prices)for price in result:   print(price)

The result produced is as follows −

100105110115
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp