What is the itertools.starmap() method in Python?
Overview
The itertools module provides functions help in iterating through iterables.
The starmap() method of the itertools module returns an iterator that applies to the given function by passing the elements of the specified iterable as arguments to the function. starmap() works similar to map() with the only difference in the way the arguments are passed to the function, meaning map() expects function(x,y) while starmap() expects function(*x).
The output of the method can be accessed in the following ways:
- Converting it to a list using
list()constructor. - Converting it to a tuple using
tuple()constructor. - Using a
forloop. - Using the
next()method on the output map object.
Note:
starmap()expects every element of the iterable to be iterable. If notTypeErroris thrown.
Syntax
itertools.starmap(function, iterable)
Parameters
function: The function to be applied.iterable: The iterable of iterables.
Applying a user-defined function
import itertoolslst = [(1, 2), (3, 4), (5, 6)]def func(x, y):return x * yret_val = itertools.starmap(func, lst)print("itertools.starmap(func(x, y), %s) = %s" % (lst, list(ret_val)))
Explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We call an iterable of iterables called
lst. - Lines 5–6: We define a function called
functhat takes two arguments and returns the product of the two arguments. - Line 8: We apply
functolstusing thestarmap()method. The result is stored inret_val. - Line 10: We print
ret_valandlst.
Applying an in-built function
import itertoolslst = [(1, 2), (3, 4), (5, 6)]ret_val = itertools.starmap(pow, lst)print("itertools.starmap(pow, %s) = %s" % (lst, list(ret_val)))
Explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We define an iterable of iterables called
lst. - Line 5: We apply the built-in
powfunction tolstusing thestarmap()method. We store the results inret_val. - Line 10: We print
ret_valandlst.
Applying a lambda function
import itertoolslst = [(1, 2), (3, 4), (5, 6)]lambda_div = lambda x, y : x/yret_val = itertools.starmap(lambda_div, lst)print("itertools.starmap(lambda_div, %s) = %s" % (lst, list(ret_val)))
Explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We define an iterable of iterables called
lst. - Line 5: We define a lambda function called
lambda_divthat takes two arguments, that is (x, y) and returns the result ofx / y. - Line 8: We apply
lambda_divtolstusing thestarmap()method. We store the results inret_val. - Line 10: We print
ret_valandlst.
The TypeError use case
import itertoolslst = [1,2,3]lambda_div = lambda x, y : x/yret_val = itertools.starmap(lambda_div, lst)print("itertools.starmap(lambda_div, %s) = %s" % (lst, list(ret_val)))
In the example above, as lst is not an iterable of iterables, the method throws a TypeError indicating that int object in lst is not an iterable.