The Python itertools.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.
SyntaxFollowing is the syntax of the Python itertools.takewhile() function −
itertools.takewhile(predicate, iterable)Parameters
This function accepts the following parameters −
This function returns an iterator that yields elements from the iterable until the predicate function returns False.
Example 1Following 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 itertools numbers = [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 −
1 4 7 9Example 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 itertools temperatures = [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 −
22 24 27 29Example 3
Now, we use itertools.takewhile() function to process a list of words, stopping when a word longer than 5 characters is encountered −
import itertools words = ["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 −
apple pear figExample 4
We can use itertools.takewhile() function to filter stock prices until a significant drop occurs −
import itertools stock_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 −
100 105 110 115
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