Skip to main content

Command Palette

Search for a command to run...

Python 01: The map() function

Updated
2 min read
Python 01: The map() function
B

Senior Test Lead || DevOps Aspirant || Python Beginner

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.

More from this blog

QA Automation Enthusiast

20 posts

I am a software testing engineer with 9+ years of experience. I am here to share my knowledge, learning and expertise with the software testing community.