DEV Community

Softhunt
Softhunt

Posted on

 

Python Map Function

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)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Output:

[20, 40, 60, 80]
Enter fullscreen mode Exit fullscreen mode

**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)
Enter fullscreen mode Exit fullscreen mode

Output:

[20, 40, 60, 80]
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

*Output:

[20, 40, 60, 80]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.