Introduction
The Python map() function returns a map object (an iterator) containing the results of applying the provided function to each item of an iterable (list, tuple, etc.)
Syntax:
map(fun, iter)
Parameters:
- fun: It is a function to which a map passes each element of a given iterable.
- iter: It is iterable which is to be mapped.
Return: It Returns a list of the results after applying the given function to each item of a given iterable (list, tuple, etc.)
Note:
– You can pass one or more iterable to the map() function.
– The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .
Code Examples
Example 01: Double all numbers using a map()
# welcome to softhunt.net
def addition(a):
return a + a
# We double all numbers using map()
num = (10, 20, 30, 40)
ans = map(addition, num)
print(list(ans))
Output:
[20, 40, 60, 80]
**Example 02: **Double all numbers using a map() and Lamda Function
# welcome to softhunt.net
# Double all numbers using map and lambda
num = (10, 20, 30, 40)
ans = map(lambda x: x + x, num)
print(list(ans)
Output:
[20, 40, 60, 80]
Example 03: Adding two lists using map() and Lamda Function
# welcome to softhunt.net
# Add two lists using map and lambda
num1 = [10, 10, 10, 10]
num2 = [10, 30, 50, 70]
ans = map(lambda x, y: x + y, num1, num2)
print(list(ans))
*Output:
[20, 40, 60, 80]
Top comments (0)