Python map() Function

Returns an interator that applies the specified function to every item in the iterable (usually a collection), and yields the results.

Syntax

Python
map(func, iterable1, iterable2, ...)

Parameters

ParameterDescription
iterable1, iterable2, ... Required. The iterable or iterables which will have the func applied to each item within.
func Required. The function that will be applied to each item in each iterator

A common use case for the map() function is to return values in the iterable that are "mapped" to new values. It is also typical to apply the list() function to evaluate the return of the map() function into a list.

Example

Python
def times5(n):
    return n * 5

nums = [1, 2, 3]
mappedNums = list(map(times5, nums))
print(mappedNums)

Output

[5, 10, 15]

Notes

The map() function is often used with lambda expressions.

Example

Python
times10 = list(map(lambda x: x * 10, [1, 2, 3]))
print(times10)

Output:

[10, 20, 30]

The map() function can also be used with more than one iterable. This is useful when mapping two or more iterables into a single collection of values. In this case, if the iterables are of different lengths, the mapping function stops when the shortest list is exhausted.

Example

Python
nums1 = [1, 2, 3]
nums2 = [10, 20, 30, 40]
added = list(map(add, nums1, nums2))
print(added)

Output:

[11, 22, 33]