Table of Contents

Definition and Usage

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Python map() function

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Syntax:

map(fun, iter)

Parameter

  • fun : It is a function to which map passes each element of given iterable.
  • iter : It is a iterable which is to be mapped.

NOTE : You can pass one or more iterable to the map() function.

Returns :

Returns a list of the results after applying the given function  
to each item of a given iterable (list, tuple etc.)

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

Example 1:

# Double all numbers using map and lambda 

numbers = (2, 4, 6, 8)
result = map(lambda x: x + x, numbers)
print(list(result))

Output:

[4, 8, 12, 16]

Example 2:

# List of strings 
l = [‘wikitechy’, ‘wiki’]

# map() can listify the list of strings individually
test = list(map(list, l))
print(test)

Output:

[[‘w’, ‘i’, ‘k’, ‘i’, ‘t’, ‘e’, ‘c’, ‘k’, ‘y’], [‘w’, ‘i’, ‘k’, ‘i’]]

Example 3:

# Python program to demonstrate working 
# of map.

# Return double of n
def addition(n):
return n + n

# We double all numbers using map()
numbers = (2, 4, 6, 8)
result = map(addition, numbers)
print(list(result))

Output:

[4, 8, 12, 16]