Python itertools.starmap() Function



The Python itertools.starmap() function is used to apply a given function to arguments taken from an iterable of tuples. It is similar to the built-in map() function but instead of taking separate arguments, it expands each tuple as function arguments.

This function is particularly useful when working with functions that take multiple arguments and when the arguments are grouped in iterable pairs.

Syntax

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

itertools.starmap(function, iterable)

Parameters

This function accepts the following parameters −

  • function: The function to apply to each tuple of arguments.
  • iterable: An iterable containing tuples, where each tuple is unpacked as arguments to the function.

Return Value

This function returns an iterator that applies the function to each tuple of arguments.

Example 1

Following is an example of the Python itertools.starmap() function. Here, we apply a multiplication function to pairs of numbers −

import itertools

def multiply(a, b):
   return a * b

pairs = [(2, 3), (4, 5), (6, 7)]
result = itertools.starmap(multiply, pairs)
for value in result:
   print(value)

Following is the output of the above code −

6
20
42

Example 2

Here, we use itertools.starmap() function to calculate the power of numbers using pow() function −

import itertools

pairs = [(2, 3), (3, 2), (4, 2), (5, 3)]
result = itertools.starmap(pow, pairs)
for value in result:
   print(value)

Output of the above code is as follows −

8
9
16
125

Example 3

Now, we use itertools.starmap() function with a function that calculates the area of a rectangle given width and height −

import itertools

def area(width, height):
   return width * height

rectangles = [(3, 4), (5, 6), (7, 2)]
result = itertools.starmap(area, rectangles)
for value in result:
   print(value)

The result obtained is as shown below −

12
30
14

Example 4

We can use itertools.starmap() function to process coordinate points by calculating their Euclidean distance from the origin −

import itertools
import math

def distance(x, y):
   return math.sqrt(x**2 + y**2)

points = [(3, 4), (5, 12), (8, 15)]
result = itertools.starmap(distance, points)
for value in result:
   print(value)

The result produced is as follows −

5.0
13.0
17.0
python_modules.htm
Advertisements