Python3 map() Function
Description
The map() function maps the specified sequence according to the provided function.
The first parameter function is called with each element in the parameter sequence, and returns a new list containing the return value of each function call.
Syntax
The following is the syntax of the map() method:
map(function, iterable, ...)
Parameters
- function -- A function
- iterable -- One or more sequences
Return Value
Returns an iterator.
Examples
The following examples demonstrate how to use map():
Python3.x Examples
>>> def square(x) : # Calculate square numbers
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # Calculate the square of each element in the list
<map object at 0x100d3d550> # Returns an iterator
>>> list(map(square, [1,2,3,4,5])) # Use list() to convert to a list
[1, 4, 9, 16, 25]
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # Use lambda anonymous function
[1, 4, 9, 16, 25]
>>>
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # Calculate the square of each element in the list
<map object at 0x100d3d550> # Returns an iterator
>>> list(map(square, [1,2,3,4,5])) # Use list() to convert to a list
[1, 4, 9, 16, 25]
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # Use lambda anonymous function
[1, 4, 9, 16, 25]
>>>
Python3 Built-in Functions