How to Create a Map Function in Python



Python


In this article, we go over how to create a map function in Python

Before we do that, let's first go over what a map function is?

A map function is basically a function that carries out its function operation on every element of a list.

The following diagram below helps to illustrate the map function in Python.

Map function in Python

As you can see from the diagram, a list is passed in to this map function. The map function then carries out its intended operation on each element of the list. The modified list (with the function carried out) is then returned as output.

So into a map() function in Python, you pass in 2 parameters. The first parameter is the function (the operation to carry out) and the second parameter is the

So this is a map function in Python.

In the following code shown below, we create a map() function that computes the square of each number in a list.



So first we create a list. This list is composed of 5 numbers: 1,2,3,4,5.

We then create a map() function and assign it to the squarenum variable.

Inside of this map() function, the function we pass in is a lambda function. Therefore, we don't have to create some external function. We create a lambda function on the spot. We then pass in the second parameter, which is our iterable object, the list.

In order to print out the resultant modified list, we have to print out the map function typed casted into a list.

We then get the numbers 1-5 squared to get 1,4,9,16,25.

What if we don't want to use a lambda function but instead just want to use a traditional function in Python created with the def keyword.

Our code would then look like the following shown below.



So if you already had an existing function created, you wouldn't need to create a lambda function. Instead you would just pass in that function as the parameter and then the list as the second parameter.

This gives us the same output as using a lambda function.

So this is how to use a map() function in Python.

The map() function is very much like a list comprehension in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...