Python map() function


The map() function in Python applies a function to each element of an iterable. This function takes two arguments first is function and the second is iterable and returns a map object.

In this article, you will learn how to use the map() function in Python.

The syntax of the Python map() function

The syntax of using the map() function in Python is given below –

map(func, iter(s))

Where,

func is the function in which all the elements of the given iterable is passed by the map function

iter(s) is one or more iterables for example list, tuple, etc which is to be mapped

Example and usage of Python map() function

We will write a program that includes a cube function and a list, we will pass the cube function and the given list as arguments to the map function. The cube function will calculate the cube of each element of the list and return a map object.

We will convert this object to a list and display the list containing cubes of elements of the given list. Now see the example which is given below.

numbers=[1,2,3,4,5]
def cube(a):
    return a*a*a
numbers_cube=list(map(cube, numbers))
print(numbers_cube)

You can see the output of this program in the given image –

By using lambda expression you can reduce the number of lines in your code. The given example shows the usage of the map() function with lambda expressions.

numbers=[1,2,3,4,5]
numbers_cube=list(map(lambda a:a*a*a, numbers))
print(numbers_cube)

When you execute this program it will produce the same result as given in the previous program.

Passing multiple iterables to map() function

You can pass more than one list, tuple, and other iterables in the map() function. You can see the example which is given below –

num1=[1,2,3]
num2=[3,4,6]
num_sum=list(map(lambda a, b:a+b,num1,num2))
print (num_sum)

This will display a list that contains the sum of elements of lists num1 and num2. You can see the output of this program in the given image –

I hope now you understand how to use the map() function in your Python code. If you have a query on this topic then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.