11.1 The itertools star map function
The itertools.starmap() function is a variation of the map() higher-order function. The map() function applies a function against each item from a sequence. The starmap(f, S) function presumes each item, i, from the sequence, S, is a tuple, and uses f(*i). The number of items in each tuple must match the number of parameters in the given function.
Here’s an example that uses a number of features of the starmap() function:
>>> from itertools import starmap, zip_longestÂ
>>> d = starmap(pow, zip_longest([], range(4), fillvalue=60))Â
>>> list(d)Â
[1, 60, 3600, 216000]
The itertools.zip_longest() function will create a sequence of pairs, [(60, 0), (60, 1), (60, 2), (60, 3)]. It does this because we provided two sequences: the [] brackets and the range(4) parameter. The fillvalue parameter is used when the shorter sequence runs out of data.
When we use the starmap() function, each pair becomes...