Tutorial Study Image

Python map()

The built-in function map() helps to execute the given function to each and every element of a specified iterable (list, tuple, set, dictionary, string, etc.) and returns a list of the results.


map(function, iterable, ...)  #where iterable can be list, tuple etc

map() Parameters:

Takes two parameters. We can pass multiple iterator objects to map() function in such case, the given function must have that many arguments.

Parameter Description Required / Optional
function The function to be called for each element of the specified iterable. Required
iterable  iterable which is to be mapped Required

map() Return Value

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

Input Return Value
 iterable   iterator object of the map class

Examples of map() method in Python

Example 1: Working of map() in python


def calculateSquare(n):
    return n*n


numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
 

Output:


{16, 1, 4, 9}

Example 2:How to use lambda function with map()?/h3>


numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
 

Output:


{16, 1, 4, 9}

Example 3: Passing multiple iterators to map() using Lambda


num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))
 

Output:

[9, 11, 13]

Example 4: Python map() with string


# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
 

Output:



A B C