The itertools
module in the standard library provides a number of convenience functions for iterating through a collection of elements efficiently.
The starmap()
function in the module is a useful tool for applying a function to a set of iterable objects. The function works like the builtin map() function except it is meant to be used with an iterable which is itself made of iterables. The function also allows functions that take multiple arguments rather than just one to be used.
starmap(function, iterable)
function |
Required. The function that will be applied to the elements of the iterable. |
iterable |
Required. The iterable object. |
The function returns an iterator object which yields the return value of applying the function to elements at each index in the iterable. In each iterations the function is called as function(*x)
where x is the current element in the iterable.
In the above example we have a list of 2-length tuples, calling starmap()
function with the builtin pow()
as the function
argument we get an iterator which yields the results of calling the pow()
function with the elements of the current tuple during each iteration as the argument. For example in the first iteration, the iterator yields the result of pow(2, 2)
, in the next iteration, pow(3, 4)
and so on.
In the above example, we have a list of tuples, we used the starmap()
function with the builtin sum()
function as the argument to get an iterator which yields the sum of the elements of each inner tuple during each iteration.