# What is the advantage of the map() function in python

created at 07-03-2021 views: 37

## introduction to python map function¶

There are some built-in higher-order functions in python, such as map(), filter(), reduce(); they are called higher-order functions because one of the parameters accepted by such functions is a function object.

map() function syntax: map(func,seq1[,seq2,……])

The first parameter received by the map function is a function object, followed by one or more sequences; the map function will apply func to each value in the following sequence and return an iterator.

example:

def func(a):
return a**2
>>>map(func,[1,2,3])
<map object at 0x000002B127AEA700>#Return a map object, which is an iterator;
>>>list(map(func1,[1,2,3]))
[1, 4, 9]
#Pass 1,2,3 as parameters into func one by one, get 1,4,9 respectively; finally convert the result to list


You can also pass in multiple sequences, one sequence corresponds to the parameter of a function; the sequence length can be inconsistent, the default is to take the sequence value of the common length;

example:

def func(a,b):
return a+b

>>>b=list(map(func,[10,20,30],[1,3,10]))#The values of the corresponding positions of the two sequences are applied to func as a and b respectively;
>>>print(b)
[11, 23, 40]#

>>>list(map(func,[10,20,30,40],[1,3,10]))#The length is inconsistent, and a sequence of the same length is taken by default
[11, 23, 40]

>>>list(map(func,[1,2,3],[10,20,30,40],[1,3,10]))#The number of sequences must be the same as the number of parameters of func
TypeError: func() takes 2 positional arguments but 3 were given
>>>b=list(map(func,[1,2,3]))
TypeError: func() missing 1 required positional argument:'b'


As you can see, the function implemented by the map() function is very similar to the for loop and the list comprehension, so what is the efficiency of the map, for loop and the list comprehension?

## comparison¶

### 1. map implementation¶

import time
start=time.time()
def func(a,b):
return a+b
c=list(map(func,range(1000000),range(1000000)))
end=time.time()
>>>end-start
0.16860485076904297


### 2. for loop implementation¶

import time
start=time.time()
c=list()
for i in range(1000000):
c.append(i+i)
end=time.time()
>>>end-start
0.2443540096282959


### 3. List comprehension implementation¶

import time
a=list(range(1000000))
b=list(range(1000000))
start=time.time()
c=[a[i]+b[i] for i in range(1000000)]
end=time.time()
print(end-start)

0.2124321460723877


From the above comparison, we can see that map has the highest efficiency and for loop has the lowest efficiency;

Based on this type of function and efficiency of map, when the project involves more loops, you can consider whether you can replace the for loop with Map. On the one hand, the code is more brief and pythonic, and on the other hand, the time efficiency of the code will be higher.

created at:07-03-2021 robot18