Exploring Map() vs. Starmap() in Python

Let’s learn about the differences

Photo by Porapak Apichodilok from Pexels.

map

map(function, iterable, ...)

Return an iterator that applies a function to every item of iterable, yielding the results. If additional iterable arguments are passed, the function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.” — Python’s documentation

  • The map() function is used to apply a function to each item in the iterable.
  • We can also pass multiple iterables, but the function mentioned should also have that many arguments (e.g. two iterables means two arguments).
  • If multiple iterables given are of different lengths, the map iterator stops when the shortest iterable is exhausted.
  • The return type is a map object.
  • A map object is an iterator.

 

Photo by the author.

We can access the map object, which is an iterator, in the following ways:

  • We can convert the map object to sequence objects like a list using a list() constructor and like a tuple using a tuple() constructor.
  • We can also iterate through the map object using a for loop.
  • We can access the element in the map object using the next() function as well.

Example 1: Applying a function to all items in one iterable using map()

  • The square() function is defined to return the square the numbers.
  • In the map function, we are passing the square() function and list object.
  • The square() function is applied to all items in the list object.
  • The return type is a map object.
  • A map object is an iterator that contains the square of all items in the iterable (list object).
  • Convert the map object to a list using a list() constructor.

https://gist.github.com/BetterProgramming/96e0eb465fd78af79bcdb80c327261d5#file-listconstructor-py

Example 2: Applying a lambda function to all items in one iterable using the map() function

https://gist.github.com/BetterProgramming/998b34d45d10dce19b756d353dde0645#file-lambdatoall-py

Example 3: Applying a function to two iterables of the same length using the map() function

  • Since two iterables are given, the function should contain two arguments.
  • The multiply(x,y) function will take the first argument x from the first iterable num1 and the second argument y from second iterable num2.

https://gist.github.com/BetterProgramming/d76049f57317e9c79437f8ce3df44503#file-multiplyxy-py

Example 4: Applying a function containing one argument to two iterables using the map() function

  • This will raise a TypeError.
  • For two iterables, the function should contain two arguments.

https://gist.github.com/BetterProgramming/6656de461848acb03e88f44efcbe79df#file-oneargtwoit-py

Example 5: Applying a function to more iterables of the same length using the map() function

https://gist.github.com/BetterProgramming/c38a23f90e73292301606004c122d2a7#file-itersamelength-py

Example 6: Applying a function to more iterables of different lengths using the map() function

  • If multiple iterables given are of different lengths, the map iterator stops when the shortest iterable is exhausted.
  • So here in this example, the shortest iterable is of length 2. So the function multiply() is applied to only two items in each iterable.

https://gist.github.com/BetterProgramming/851571de2eea84a5a7d77e02a1a40713#file-iterdifflengths-py

Example 7: Iterating through a map object using a for loop

https://gist.github.com/BetterProgramming/6f76bc24bd92b09782a0825710c70497#file-mapforloop-py

Example 8: Accessing elements in the map object using the next() function

  • A map object is an iterator. So we can access the next element in the map object using the next() function.

https://gist.github.com/BetterProgramming/fe4a208e7b1ce2ec26255bcb3ace0837#file-nextfunc-py

Example 9: Applying a built-in function to an iterable (string) using the map() function

colors=['red','yellow','blue']
s=list(map(str.upper,colors))
print (s)#Output:['RED', 'YELLOW', 'BLUE']

Example 10: Applying a function to an iterable (tuple) using the map() function

def square(x):
    return x*x
t1=(1,2,3)
s=tuple(map(square,t1))
print (s)#Output:(1, 4, 9)

itertools.starmap()

itertools.starmap(function, iterable)

Make an iterator that computes the function using arguments obtained from the iterable. Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c).” — Python’s documentation

  • First, we have to import the itertools module.
  • The starmap method is supported by the itertools module only.
  • starmap(function, iterable) → The function and iterable are passed to the starmap method.
  • Items inside the iterable should also be iterable. Otherwise, it will raise a TypeError.
  • The return type is an itertools.starmap object.
  • The starmap object is an iterator.

We can access the starmap object, which is an iterator, in the following ways:

  • We can convert the starmap object to sequence objects like a list using a list() constructor or a tuple using a tuple() constructor.
  • We can also iterate through the map object using a for loop.
  • We can access the element in the starmap object using the next() function as well.

 

Image by Author

Example 1: Applying a user-defined function to a list of tuples using starmap()

https://gist.github.com/IndhumathyChelliah/ecf78aedc5cdff97caed6ee54769f910

Example 2: Applying pow() to a list of tuples using starmap()

https://gist.github.com/BetterProgramming/58b9c2e781ac6ecb86a12a2320859c8b#file-powtuples-py

Using map():

num=map(pow,[0,1,2],[2,2,2])
print (list(num))
#Output:[0, 1, 4]

Example 3: If elements inside the iterable are not iterable, it will raise a TypeError

import itertools
num=itertools.starmap(lambda x:x**2,[1,2,3])
print (list(num))
#Output:TypeError: 'int' object is not iterable

Example 4: Applying a lambda function to a list of tuples using starmap()

import itertools
num=itertools.starmap(lambda x,y:x+y,[(0,1),(1,2),(2,3)])
print (list(num))#Output:[1, 3, 5]

Example 5: Accessing items in the starmap object using a for loop

https://gist.github.com/BetterProgramming/ae7520645e8835c76ad052820f862f3f#file-starmapforloop-py

Example 6: Accessing items in the starmap object using the next() method

  • A map object is an iterator. So we can access the next element in the map object using the next() function.
import itertools
num=itertools.starmap(lambda x,y:x+y,[(0,1),(1,2),(2,3)])
print (next(num))#Output:1
print (next(num))#Output:3
print (next(num))#Output:5

Conclusion

  • map(): Multiple iterables are allowed.
  • starmap(): Only one iterable is allowed. Items inside the iterable should also be iterable.
  • Both the map object and starmap object are iterators.
  • map(): Built-in function.
  • itertools.starmap(): You have to import the itertools module.

Resources

My blog links

reduce() vs accumulate()

filter() vs filterfalse()

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s