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
map(function, iterable, ...)
where
Parameter | Required/Optional | Description |
---|---|---|
function | Mandatory | A callable function. |
iterable | Mandatory | An iterable object like list, tuple, set, etc. |
… | Optional | More 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
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
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.