What is the itertools.pairwise() method in python?

Overview

The itertools module in Python provides functions. These functions help in iterating through iterables.

The pairwise() method in the itertools module returns the successive overlapping pairs taken from the input iterable. The sequence of the output pairs is in the order of the elements in the iterable. This functionality was introduced in Python version 3.10.

Syntax

itertools.pairwise(iterable)

Parameters

This method takes a parameter, iterables, which represents the iterable.

Example

from itertools import pairwise
lst = [1,2,3,4,5]
print("Original list - ", lst)
print("Successive overlapping pairs - ", list(pairwise(lst)))
string = "hello educative"
print("Successive overlapping pairs of characters in a string- ", list(pairwise(string)))

Explanation

  • Line 1: We import the pairwise function from the itertools module.
  • Line 3: We define a list of numbers called lst.
  • Line 4: We print lst.
  • Line 5: We obtain successive overlapping pairs by invoking the pairwise function with lst as the argument.
  • Line 7: We define a string called string.
  • Line 8: We obtain a successive overlapping pairs of characters by invoking the pairwise function with string as the argument.

Note: A string is iterable in python.

Free Resources