Python itertools.pairwise() Function
The Python itertools.pairwise() function is used to create an iterator that returns consecutive overlapping pairs from an iterable. It is useful for analyzing sequential relationships between elements in a dataset.
This function is equivalent to using the zip function with a slice of the original iterable.
Syntax
Following is the syntax of the Python itertools.pairwise() function −
itertools.pairwise(iterable)
Parameters
This function accepts the input iterable as a parameter from which consecutive pairs will be extracted.
Return Value
This function returns an iterator that yields tuples containing consecutive elements from the input iterable.
Example 1
Following is an example of the Python itertools.pairwise() function. Here, we extract consecutive pairs from a list of numbers −
import itertools numbers = [1, 2, 3, 4, 5] pairs = itertools.pairwise(numbers) for pair in pairs: print(pair)
Following is the output of the above code −
(1, 2) (2, 3) (3, 4) (4, 5)
Example 2
Here, we use itertools.pairwise() function on a string to generate consecutive character pairs −
import itertools text = "HELLO" pairs = itertools.pairwise(text) for pair in pairs: print(pair)
Output of the above code is as follows −
('H', 'E')
('E', 'L')
('L', 'L')
('L', 'O')
Example 3
Now, we use itertools.pairwise() function to analyze temperature differences between consecutive days −
import itertools temperatures = [72, 75, 78, 74, 70, 69] differences = [(b - a) for a, b in itertools.pairwise(temperatures)] print(differences)
The result obtained is as shown below −
[3, 3, -4, -4, -1]
Example 4
We can also use the itertools.pairwise() function to check for increasing trends in stock prices −
import itertools stock_prices = [100, 102, 101, 105, 107, 106] increasing_trend = [b > a for a, b in itertools.pairwise(stock_prices)] print(increasing_trend)
The result produced is as follows −
[True, False, True, True, False]
python_modules