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:
list()
constructor.tuple()
constructor.for
loop.next()
method on the output map object.Note:
starmap()
expects every element of the iterable to be iterable. If notTypeError
is thrown.
itertools.starmap(function, iterable)
function
: The function to be applied.iterable
: The iterable of iterables.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)))
itertools
module.lst
.func
that takes two arguments and returns the product of the two arguments.func
to lst
using the starmap()
method. The result is stored in ret_val
.ret_val
and lst
.import itertoolslst = [(1, 2), (3, 4), (5, 6)]ret_val = itertools.starmap(pow, lst)print("itertools.starmap(pow, %s) = %s" % (lst, list(ret_val)))
itertools
module.lst
.pow
function to lst
using the starmap()
method. We store the results in ret_val
.ret_val
and lst
.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)))
itertools
module.lst
.lambda_div
that takes two arguments, that is (x, y) and returns the result of x / y
.lambda_div
to lst
using the starmap()
method. We store the results in ret_val
.ret_val
and lst
.TypeError
use caseimport 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.