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.
map()
function is used to apply a function to each item in the iterable.We can access the map object which is an iterator using below mentioned ways.
Example 1: Applying a function to all items in one iterable using map()
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.
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