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.
map(function,iterable,...)
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
Note
The map()
function does not change the original list, but returns a new list.
Programming example:
del square(x):
return x ** 2
map(square,[1,2,3,4,5])
# The results are as follows:
[1,4,9,16,25]
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.
[3,7,11,15,19]
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.
[(8,5),(16,6),(6,7)]
When no function is passed in, map()
is equivalent to zip()
, combining multiple elements in the same position in a list into a tuple.
map(None,[2,4,6],[3,2,1])
# 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.
map(int,(1,2,3))
# The results are as follows.
[1,2,3]
Convert string to list.
map(int, '1234')
# The results are as follows.
[1,2,3,4]
Extract the key from the dictionary and put the result in a list:.
map(int,{1:2,2:3,3:4})
# The results are as follows.
[1,2,3]
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
Results
[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
[25, 10]
[36, 12]
[49, 14]
[64, 16]
[81, 18]