Python 01: The map() function

Python 01: The map() function

Table of contents

What is a map?

map() is a function in Python programming and it takes two arguments. The first argument is function(), and the second argument is an iterable like a list, tuple etc.

map() functionality - each item of the second argument (iterable) will be passed to the function() (first argument). The function() processes or performs some operation on each received argument and returns the result to the map object.

Pictorial representation of the map() functionality.

map.png

The return type of the map() is a map object. Passing this map object to list() or set() returns iterable respectively.

Example 1: Converting a list of integers to a list of squares of the integers.

In the below example, we have a list of integers, and a function() called square(). The square() function takes an integer and returns a square of it.

numbers = [3, 5, 7, 9, 11] # a list

def square(x):
    # a method returns square of a given number
    return x * x

if __name__ == "__main__":
    result = map(square, numbers)
    print("The return type of map is : "+result)

The result of the above execution is a map object as shown below.

The return type of map is <map object at 0x000002C6D391F610>

Now if we pass the map object to a list, it returns a modified list. Check the code snippet below.

numbers = [3, 5, 7, 9, 11] # a list

def square(x):
    # a method returns square of a given number
    return x * x

if __name__ == "__main__":
    result = map(square, numbers)
    squared_list = list(result)    
    print(f"The return type of map is {squared_list}")

The result is

The return type of map is [9, 25, 49, 81, 121]

Thanks for reading. Keep learning.

Did you find this article valuable?

Support QA Automation Enthusiast by becoming a sponsor. Any amount is appreciated!