Python map()

The map() function applies a given function to each item of an iterable (list, tuple etc.) and returns a list of the results.

The syntax of map() is:

map(function, iterable, ...)

1. map() Parameter

  • function – map() passes each item of the iterable to this function.
  • iterable – iterable which is to be mapped

You can pass more than one iterable to the map() function.

2. Return Value from map()

The map() function applies a given to function to each item of an iterable and returns a list of the results.

The returned value from map() (map object) can then be passed to functions like list() (to create a list), set() (to create a set) and so on.

3. Example 1: Working of map()

def calculateSquare(n):
    return n*n


numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

Output

<map object at 0x7f722da129e8>
{16, 1, 4, 9}

In the above example, each item of the tuple is squared.

Since map() expects a function to be passed in, lambda functions are commonly used while working with map() functions.

A lambda function is a short function without a name. Visit this page to learn more about Python lambda Function.

4. Example 2: How to use lambda function with map()?

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

Output

<map 0x7fafc21ccb00>
{16, 1, 4, 9}

There is no difference in functionalities of this example and Example 1.

5. Example 3: Passing Multiple Iterators to map() Using Lambda

In this example, corresponding items of two lists are added.

num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))

Output

[9, 11, 13]