map

Full name
map
Library
Built-in
Syntax

map(function, iterable [, iterable...])

Description

The map function applies a function to the values of the iterable that we specify as an argument. In the case that two or more iterables are specified as arguments, the function will consider their values in parallel, stopping returning values as soon as the end of the shortest iterable is reached (see examples below).

Parameters
  • function: Function to apply to the elements of the iterable.
  • iterable: Iterable to whose elements the function will be applied.
Result

The map function returns an iterable.

Examples

If we start from an iterable such as, for example, a list:

a = [1, 2, 3, 4]

...we can apply a function to it that squares its values with the following code:

def squared(n):
    return n ** 2

map(squared, a)

As we can see, the result is an object of type map:

type(map(squared, a))

map

If we want to visualize its content we can convert it into, for example, a list:

list(map(squared, a))

[1, 4, 9, 16]

In a case like the previous one, it is much more practical to define the function as a lambda function directly as an argument to map:

list(map(lambda n: n ** 2, a))

[1, 4, 9, 16]

If the map function receives two or more iterables as arguments, it will apply the specified function to the elements of the iterables in parallel. For example, suppose we start from the following two lists:

a = [1, 2, 3, 4]
b = [2, 4, 6, 8]

If we want to add their values two by two, we can do it by defining a function that receives two values and returns their sum, and use this function as the first argument of map:

def addition(m, n):
    return m + n

list(map(addition, a, b))

[3, 6, 9, 12]

As we can see, the result has been calculated by adding the first element of "a" with the first element of "b", the second of "a" with the second of "b", and so on.

Again, here too we could choose to use a lambda function as the first argument:

list(map(lambda m, n: m + n, a, b))

[3, 6, 9, 12]

If the iterables included as arguments do not have the same number of elements, the map function applies the function in parallel until reaching the end of the shortest iterable.

For example, if we start from the following three lists with 5, 3 and 4 elements respectively:

a = [1, 2, 3, 4, 5]
b = [2, 4, 6]
c = [1, 2, 4, 8]

...and we apply a function that, for example, adds its elements:

list(map(lambda m, n, r: m + n + r, a, b, c))

[4, 8, 13]

...we see that only values are returned for the first three elements.

Submitted by admin on Thu, 01/14/2021 - 17:07