Python – Itertools.starmap()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is starmap().
Note: For more information, refer to Python Itertools
When an iterable is contained within another iterable and certain function has to be applied on them, starmap() is used. The starmap() considers each element of the iterable within another iterable as a separate item. It is similar to map(). This function comes under the category terminating iterators.
The function can be a built-in one or user-defined or even a lambda function. To understand the difference between map() and starmap() look at the code snippets below :
TypeError Traceback (most recent call last) in 1 li=[(2, 5), (3, 2), (4, 3)] ----> 2 new_li=list(map(pow, li)) 3 print(new_li) TypeError: pow expected at least 2 arguments, got 1
Here, the map considers each tuple within the list as a single argument and thus the error raises. The starmap() overcomes this issue. Look at the code snippet below:
[32, 9, 64]
The internal working of the starmap() can be implemented as given below.
def startmap(function, iterable): for it in iterables: yield function(*it)
Here ‘it’ also denotes an iterable.
Let us look at another example that differentiates map() and starmap(). We can apply a function to each element in the iterable using map(). To say we need to add a constant number to each element in the lists, we can use map().
[4, 5, 6, 7, 8, 9]
What if we want to add different numbers to different elements of the list ?
Now, starmap() must be used.
[5, 4, 10, 8, 11, 9]
Practical example of using starmap():
Consider a list containing coordinates of various triangles. We are supposed to apply Pythagoras theorem and find output which coordinates form a right-angled triangle. It can be implemented as given below :
tuples which form right angled triangle : [False, True, True, False, False]
The right triangle coordinates are :(3, 4, 5) (6, 8, 10)