map vs itertools.starmap

map

map(functioniterable)

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.

  • map() function is used to apply a function to each item in the iterable.
  • We can pass multiple iterables also. But the function mentioned should also have that many arguments. (ex. 2 iterables means 2 arguments )
  • If multiple iterables given are of different lengths, the map iterator stops when the shortest iterable is exhausted.
  • Return type is a** map object.**
  • map object is an iterator.

Image for post

We can access the map object which is an iterator using below mentioned ways.

  • We can convert the map object to sequence objects like list using **list() **constructor, tuple using tuple() constructor.
  • We can iterate through the map object using** for loop** also
  • We can access the element inthe** map object using the next()** function also.

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

  • **square() **function is defined to return the square the numbers.
  • In the map function, we are passing square() function and list object.
  • square() function is applied to all items in the list object.
  • Return type is map object.
  • map object is an** iterator** which contains the square of all items in the iterable(list object)
  • Converting the map object to** list** using list() constructor.
def square(x):
    return x*x

l1=[1,2,3,4]
s=map(square,l1)
#Returns a map object
print (s)#Output:<map object at 0x0158E4D8>
print (type(s))#Output:<class 'map'>
#converting map object to list() constructor.
print (list(s))#Output:[1, 4, 9, 16]

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

l1=[1,2,3,4]

s=map(lambda x:x*x,l1)
#Returns a map object
print (s)#Output:<map object at 0x0158E4D8>
print (type(s))#Output:<class 'map'>
#converting map object to list() constructor.
print (list(s))#Output:[1, 4, 9, 16]

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

  • Since two iterables are given, the function should contain two arguments.
  • multiply(x,y) function will take the first argument x from the first iterable l1 and the second argument y from second iterable l2
def multiply(x,y):
    return x*y

l1=[1,2,3,4]
l2=[2,4,6,8]

s=map(multiply,l1,l2)

#Returns a map object
print (s)#Output:<map object at 0x0158E4D8>
print (type(s))#Output:<class 'map'>

#converting map object to list() constructor.
print (list(s))#Output:[2, 8, 18, 32]

#python3 #python

Map vs itertools.starmap in Python
13.00 GEEK