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

starmap() function

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.

Syntax :

starmap(function, iterable)

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 :



filter_none

edit
close

play_arrow

link
brightness_4
code

li =[(2, 5), (3, 2), (4, 3)]
  
new_li = list(map(pow, li))
  
print(new_li)

chevron_right


Output:

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

from itertools import starmap
  
li =[(2, 5), (3, 2), (4, 3)]
  
new_li = list(starmap(pow, li))
  
print(new_li)

chevron_right


Output:

[32, 9, 64]

The internal working of the starmap() can be implemented as given below.

def startmap(function, iterable):
  
   for it in iterables:
       yeild 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().

filter_none

edit
close

play_arrow

link
brightness_4
code

li =[2, 3, 4, 5, 6, 7]
  
# adds 2 to each element in list
ans = list(map(lambda x:x + 2, li))
  
print(ans)

chevron_right


Output:

[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.

filter_none

edit
close

play_arrow

link
brightness_4
code

from itertools import starmap
  
li =[(2, 3), (3, 1), (4, 6), (5, 3), (6, 5), (7, 2)]
  
ans = list(starmap(lambda x, y:x + y, li))
  
print(ans)

chevron_right


Output:

[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 out out which coordinates form a right-angled triangle. It can be implemented as given below :

filter_none

edit
close

play_arrow

link
brightness_4
code

from itertools import starmap
  
  
co_ordinates =[(2, 3, 4), 
               (3, 4, 5),
               (6, 8, 10),
               (1, 5, 7),
               (7, 4, 10)]
  
  
# Set true if coordinates form
# a right-triangle else false
right_triangles = list(starmap(lambda x, y, z:True
                               if ((x * x)+(y * y))==(z * z)
                               else False, co_ordinates))
  
print("tuples which form right angled triangle :"
      right_triangles, end ="\n\n")
  
print("The right triangle coordinates are :"
      end ="")
  
# to print the coordinates
for i in range (0, len(right_triangles)):
      
    if right_triangles[i]== True:
          
        print(co_ordinates[i], end =" ")

chevron_right


Output:

tuples which form right angled triangle : [False, True, True, False, False]

The right triangle coordinates are :(3, 4, 5) (6, 8, 10)

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

I am Akshaya E, currently a student at NIT, Trichy I have keen interest in sharing what I know to people around me I like to explain things with easy and real-time examples I am even writing a blog where I teach python from scratch

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.