Python map() function
 

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.

Previous Python enumerate() function
Next Python filter() function
 

About author

You might also like

Programming 0 Comments

Scope of variables in Python

A variable in Python is used to store a value in the memory. The value of a variable can be changed later in the program. Python is a dynamically typed

Programming 0 Comments

Variables and Constants In Python

A variable in Python is used to store a value in the memory. The value of a variable can be changed later in the program. In Python programming, a variable

Programming 0 Comments

Type Conversion in Python

The data type is the classification of data items it tells the interpreter how a user is intended to use the data. Python has various data types and a variable

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Reply