map() method in Python

Introduction to the map() function and syntax. map is a python built-in function that maps the specified sequence based on the provided function.

The concept of map is often used in functional programming languages, where a function is applied to a sequence. For Python, it is applied to an iterable.

Related course: Complete Python Programming Course & Exercises

map() syntax

The format of the map() function is.


The first argument accepts a function name, and the subsequent arguments accept one or more iterable sequences, returning a collection.

Python map examples

What map() does is apply the specified function to each element of the list in turn, get a new list is returned.

Thus you have two parmeters:

  • the function to apply
  • the list to apply it to


The map() function does not change the original list, but returns a new list.

Programming example:

del square(x):
    return x ** 2


# The results are as follows: 

map method in python

Using the map() function by using the lambda anonymous function method.

map(lambda x, y: x+y,[1,3,5,7,9],[2,4,6,8,10])

# The results are as follows.

Make the return value a tuple by the lambda function.

map(lambdax, y : (x**y,x+y),[2,4,6],[3,2,1])

# The results are as follows.

When no function is passed in, map() is equivalent to zip(), combining multiple elements in the same position in a list into a tuple.


# The results are as follows.
[(2,3), (4,2), (6,1)]

Type conversion with map()

Type conversion is also possible with map().

Converting a tuple to a list.


# The results are as follows.

Convert string to list.

map(int, '1234')

# The results are as follows.

Extract the key from the dictionary and put the result in a list:.


# The results are as follows.

function with map

In addition to accepting a list, map() can also accept a function of a list

def multiply(x):
    return x*x

def add(x):
    return x+x

func = [multiply, add]

for i in range(10):
    value = map(lambda x:x(i), func)
    print func


[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
[25, 10]
[36, 12]
[49, 14]
[64, 16]
[81, 18]