Python map()

Python map() builtin function that applies given function on each item in the iterable(s) and returns a map object.

In this tutorial, we will learn about the syntax of Python map() function, and learn how to use this function with the help of examples.

Syntax

The syntax of map() function is

</>
Copy
map(function, iterable, ...)

where

ParameterRequired/OptionalDescription
functionMandatoryA callable function.
iterableMandatoryAn iterable object like list, tuple, set, etc.
OptionalMore iterable objects on whose items the function has to be applied in parallel.

Returns

The function returns an iterable object of type map.

Examples

1. Increment each value of list using map()

In this example, we will define a function that returns a value incremented by 0.5, and call map() function with this function and a list passed as arguments.

Python Program

</>
Copy
def func(a):
    return a + 0.5

x = [2, 4, 6, 8]

result = map(func, x)
for item in result:
    print(item)

Output

2.5
4.5
6.5
8.5

2. map() with Multiple Iterables

In this example, we will give two iterables along with a function. The function should process corresponding items from each iterable parallelly during an iteration.

Python Program

</>
Copy
def func(a, b):
    return a + b

x = [2, 4, 6, 8]
y = [0.1, 0.2, 0.3, 0.4]

result = map(func, x, y)
for item in result:
    print(item)

Output

2.1
4.2
6.3
8.4

Conclusion

In this Python Tutorial, we have learnt the syntax of Python map() builtin function, and also learned how to use this function, with the help of Python example programs.