avatarIndhumathy Chelliah

Summary

The web content provides an in-depth comparison between Python's built-in map() function and the itertools.starmap() method, illustrating their usage with examples and highlighting the differences in how they handle iterables.

Abstract

The article "Exploring Map() vs. Starmap() in Python" delves into the functionalities of map() and itertools.starmap(), two Python tools used for applying a function to iterables. The map() function is versatile, accepting multiple iterables and applying a function to each item in parallel, stopping when the shortest iterable is exhausted. It returns an iterator that can be converted to various sequence types or iterated over directly. In contrast, itertools.starmap() is designed to work with a single iterable where each item is itself iterable, effectively applying a function to a list of tuples or similar structures. The article includes numerous examples demonstrating the application of these functions, including error handling when iterables are not of the correct form. The conclusion summarizes the key differences: map() allows multiple iterables, while starmap() requires items within a single iterable to be iterable themselves. Both functions return iterator objects, but starmap() is only accessible through the itertools module, which must be imported.

Opinions

  • The author emphasizes the practicality of map() for applying a function across multiple iterables simultaneously, which can be particularly useful in parallel processing scenarios.
  • The article suggests that starmap() is preferable when dealing with pre-zipped data, as it can directly apply a function to each tuple in a single iterable without the need for additional unpacking.
  • The author provides a clear recommendation for readers to follow their Medium account for more Python and Data Science tutorials, indicating a commitment to ongoing educational content in these areas.
  • By including a promotion for ZAI.chat, the author endorses this AI service as a cost-effective alternative to ChatGPT Plus (GPT-4), implying satisfaction with its performance and value.

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.

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

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.

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.

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

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.

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

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.

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()

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

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

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()

Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter.

Thanks for reading!

Python3
Python
Artificial Intelligence
Women In Tech
Technology
Recommended from ReadMedium