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.


def func(a):
    return a**2
<map object at 0x000002B127AEA700>#Return a map object, which is an iterator;
[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;


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;
[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
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?


1. map implementation

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

2. for loop implementation

import time
for i in range(1000000):

3. List comprehension implementation

import time
c=[a[i]+b[i] for i in range(1000000)]


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
edited at: 07-03-2021: