Python map() Function
Description
map() Applies a given function to each item of a specified sequence, producing a mapping.
The first argument function is called with each element of the parameter sequence, returning a new list containing the return value of each function call.
Syntax
map() function syntax:
map(function, iterable, ...)
Parameters
- function -- a function
- iterable -- one or more sequences
Return Value
Python 2.x returns a list.
Python 3.x returns an iterator.
Example
The following example shows how to use map():
Python 2.x example
def
square
(
x
)
:
Calculate squares
...
return
x **
2
...
map
(
square
,
[
1
,
2
,
3
,
4
,
5
]
)
Calculate the square of each element in a list
[
1
,
4
,
9
,
16
,
25
]
map
(
lambda
x: x **
2
,
[
1
,
2
,
3
,
4
,
5
]
)
Use a lambda anonymous function
[
1
,
4
,
9
,
16
,
25
]
Two lists are provided, and the elements at the same positions are added together
map
(
lambda
x
,
y: x + y
,
[
1
,
3
,
5
,
7
,
9
]
,
[
2
,
4
,
6
,
8
,
10
]
)
[
3
,
7
,
11
,
15
,
19
]
Python3.x example
def
square
(
x
)
:
Calculate squares
...
return
x **
2
...
map
(
square
,
[
1
,
2
,
3
,
4
,
5
]
)
Calculate the square of each element in a list
<
map
object
at
0x100d3d550
Returns an iterator
list
(
map
(
square
,
[
1
,
2
,
3
,
4
,
5
]
)
)
Convert to a list using list()
[
1
,
4
,
9
,
16
,
25
]
list
(
map
(
lambda
x: x **
2
,
[
1
,
2
,
3
,
4
,
5
]
)
)
Use a lambda anonymous function
[
1
,
4
,
9
,
16
,
25
]
Python built-in function