Starmap()

`starmap()` accepts another function and an iterable object as arguments, where the elements of the iterable are tuples. The passed function is applied to each tuple, with the tuple being unpacked and its elements passed as separate arguments to the function.

Thus, `starmap()` can be used instead of `map()` if the data has already been packed into tuples. 

In the example, `starmap()` allows the calculation of the squares of numbers in tuples within a list and then sums them up.

from itertools import starmap

numbers = [(1, 2), (3,4), (5,6)]
squares = starmap(lambda x, y: x**2 + y**2, numbers)

for square in squares: print(square) # -> 5 25 61

Comments (0)

Leave a comment