Python map() Function

Python 内置函数Python Built-in Functions


Description

map()Maps the specified sequence according to the provided function.

The first parameter function calls the function with each element in the parameter sequence, returning a new list containing the return value of each function call.

Syntax

map() function syntax:

map(function, iterable, ...)

Parameters

  • function -- Function
  • iterable -- One or more sequences

Return Value

Python 2.x returns a list.

Python 3.x returns an iterator.

Examples

The following examples demonstrate how to use map():

Python2.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
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # Use lambda anonymous function
[1, 4, 9, 16, 25]

# Two lists are provided, adding the data at the same positions
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

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]
>>>

Python 内置函数Python Built-in Functions

Other Extensions