Python map() function – How to map a function with multiple arguments


To map a function with multiple arguments in Python, we need to pass multiple iterables to the map() function.

In today’s post, we’ll learn to do that.

We’ll first look at what the map() function does and how to use it with single argument functions.

Next, we’ll discuss how to use the Python map() function with multiple arguments functions. We’ll also discuss how to set default argument values when using the function and how the map() function differs in Python 2 and Python 3.

Finally, we’ll work on a practice question where we use the map() function to calculate the Euclidean distance between two points.

Let’s get started.

Using the Python map() function with single argument functions

The map() function is a built-in function in Python that allows us to apply a function to all the elements in an iterable (such as a list or tuple). For instance, suppose we have a list of numbers and we want to square all the numbers in the list, we can do it with the map() function.

The syntax of the map() function is as follows:

map(<name of function to apply>, <name(s) of iterable(s)>)

The map() function returns a map object, which can be converted to an iterable such as a tuple, set or list.

Let’s look at some examples:

Using Named Function

Example 1 – Using Python map() with single argument named function

# Example 1

myList = [1, 2, 3, 4, 5]

def getSq(x):
    return x**2

sq_map = map(getSq, myList)
sq_list = list(sq_map)

print(sq_list)

Here, we first declare a list called myList.

Next, we define a function called getSq() that accepts an argument x and returns the value of x, raised to the power of 2 (i.e. the square of x).

On line 8, we pass the name of the getSq() function and the myList iterable to the map() function.

This function iterates through myList and passes each element in myList to the getSq() function.

This is similar (but not identical) to using the following for loop to call the getSq() function:

result = []
mySquare = 0

for num in myList:
    mySquare = getSq(num)
    result.append(mySquare)

In the for loop above, we append the results returned by the getSq() function to a list (result).

When we use the map() function, the results returned by the getSq() function are not stored in a list. Instead, the results are stored in a map object, which is returned by the map() function after it completes its task.

We store this map object in a variable called sq_map on line 8 in Example 1.

On line 9, we pass this map object to the built-in list() function to convert it back to a list.

Finally, we print the list on line 11.

If you run Example 1 above, you’ll get the following output:

[1, 4, 9, 16, 25]

Using Lambda Function

In the example above, the getSq() function only does one task – return the value of x raised to the power of 2. For a simple function like this, it is easier to replace it with a lambda function. If you are unfamiliar with lambda functions, you can check out the post here to find out how lambda function works.

Here’s how we can replace the getSq() function in Example 1 with a lambda function:

Example 2 – Using Python map() with single argument lambda function

# Example 2

myList = [1, 2, 3, 4, 5]

sq_map = map(lambda x : x**2, myList)

sq_list = list(sq_map)

print(sq_list)

This example does exactly the same thing as Example 1. The only difference is we replaced the getSq() function with the following lambda function:

lambda x : x**2

If you run Example 2 above, you’ll get the following output:

[1, 4, 9, 16, 25]

Using the Python map() function with multiple arguments functions

Besides using the Python map() function to apply single argument functions to an iterable, we can use it to apply functions with multiple arguments. To do that, we need to ensure that the number of arguments matches the number of iterables.

Let’s look at an example.

Using Named Function

Example 3 – Using Python map() with multiple arguments named function

# Example 3

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]

def getSum(x, y):
    return x + y

result = list(map(getSum, list1, list2))

print(result)

Here, the getSum() function (lines 6 and 7) has two arguments – x and y. It finds the sum of the arguments and returns the result.

Since the getSum() function has two arguments, we need to pass two iterables to the map() function when calling the function. We do that on line 9, passing the getSum() function and the list1 and list2 iterables to the map() function.

Next, we pass the result of the map() function to the list() function to convert it to a list, and assign the list to a variable called result.

Finally, we print the value of result on line 11.

If you run the code above, you’ll get the following output:

[7, 9, 11, 13, 15]

We get 7 for the first element as the first element in list1 is 1 while the first element in list2 is 6. Therefore, x + y = 1 + 6, which gives us 7.

The same applies for the other elements in result.

Using Lambda Function

We can replace the getSum() function in Example 3 with a lambda function, as shown in the code below:

Example 4 – Using Python map() with multiple arguments lambda function

# Example 4

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]

result = list(map(lambda x, y: x + y, list1, list2))

print(result)

Here, we replace the getSum() function in Example 3 with the following lambda function:

lambda x, y: x + y

This lambda function accepts two inputs – x and y – and returns the sum of the inputs (x + y).

If you run the example above, you’ll get the same output as Example 3.

Using the map() function with default argument values for the function to be applied

When using the map() function, it is possible to pass default argument values for the function that we want to apply to the iterable(s).

To do that, we need to use the partial() function in the functools module.

Let’s look at an example:

Example 5 – Using default argument values for the function to be applied

# Example 5

from functools import partial

list1 = [1, 2, 3, 4, 5]

def getSum(x, y):
    return x + y

partial_func = partial(getSum, y = 10)

result = list(map(partial_func, list1))

print(result)

Here, we first import the built-in partial() function from the functools module on line 3.

Next, we declare and initialize a list called list1 on line 5.

On lines 7 and 8, we define the getSum() function that accepts two arguments and returns the sum of the arguments. This function is identical to the getSum() function in Example 3.

However, instead of passing the getSum() function directly to the map() function in this example, we’ll use the partial() function to specify a default value for the argument y first.

To do that, we need to pass the getSum() function and the default value for y to the partial() function. We do that on line 10.

The partial() function replaces the second argument for getSum() with the value 10 and returns a partial object. This partial object behaves like the getSum() function when called, except that instead of having two arguments, it only has one argument – x. This is because the second argument has been replaced with the value 10. Other than that, the partial object behaves like a normal function.

We assign this partial object to a variable called partial_func and pass this object and the list1 iterable to the map() function on line 12.

Notice that we do not need to pass a second iterable to the map() function this time? This is because as mentioned above, partial_func only has one argument – x. The second argument – y – in getSum() has been replaced with the value 10.

We pass the result of the map() function to the list() function on line 12 and assign the resulting list to a variable called result.

Finally, we print the value of result on line 14.

If you run the code above, you’ll get the following output:

[11, 12, 13, 14, 15]

Differences between Python 2 and Python 3 for the map() function with multiple arguments

Now that you’ve seen various examples of how the map() function works, let’s discuss an important difference between Python 2 and 3 in terms of how the function behaves when we pass iterables of varying lengths to the function.

Let’s look at an example:

Example 6 – Passing iterables of different lengths

# Example 6

def getSum(x, y):
  return x + y

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7]

result = list(map(getSum, list1, list2))

print(result)

Here, we have the getSum() function on lines 3 and 4. This function is the same as the ones we used in examples 3 and 5.

However, in this example, we’ll pass the getSum() function and two lists of different lengths to the map() function.

Python 3

If we run the code above in Python 3, we’ll get the following output:

[6, 8, 10]

Notice that the output only has 3 elements? This is because in Python 3, the map() function stops once it reaches the end of any of the iterables we pass to it. Hence, it stops when it reaches the end of list2, which only has three elements.

Python 2

In contrast, if we run the code above in Python 2, we get an error, as shown in the image below:

Python 2 map function - multiple arguments of different lengths

 

This is because in Python 2, the map() function runs until it reaches the end of the longest iterable. In other words, in Example 6, it runs until the end of list1.

In order to do that, the map() function replaces any missing element in list2 with a special value called None. That’s why we get the error message “unsupported operand type(s) for +: ‘int’ and ‘NoneType’” when we try to run the code.

If you want to prevent this error message, you’ll have to ensure that you always pass iterables of the same length to the map() function if you use Python 2.

Alternatively, you can replace None with other values when you define the function that you want to apply using the map() function. An example is shown below:

Example 7 – Passing iterables of different lengths (None replaced by 0)

# Example 7

def getSum(x, y):
    if x is None:
        x = 0
    elif y is None:
        y = 0
    return x + y

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7]

result = list(map(getSum, list1, list2))

print(result)

If you run the code above in Python 2, you’ll get the following output:

[6, 8, 10, 4]

If you run it in Python 3, you’ll get the following output:

[6, 8, 10]

Practice Question

Now that we are comfortable with the map() function, let’s move on to the practice question for today.

Today’s practice question requires us to write a function called getDist() that accepts two tuples. These tuples represent the coordinates of two points in an Euclidean space.

Don’t worry if this sounds complicated. Let’s just consider the most common case where the points are in a 2D space. The tuple will then be of the form (x, y), where x stands for the x-coordinate of the point and y stands for the y-coordinate.

Our job is to write a function that returns the Euclidean distance between the two points.

Suppose the two points are in a n-dimensional space and represented by (p1, p2, p3, …, pn) and (q1, q2, q3, …, qn), the distance is given by the formula:

Euclidean Distance

For instance, if n = 2 and the points are (3, 5) and (7, 2), the distance is

Euclidean Dist Example

Our job now is to write a function that does this calculation for us and returns the result as a floating-point number in 2 decimal places.

The function should make use of the map() function. Try doing this yourself. You can assume that the tuples passed to the function are of equal length.

Expected Results

To test your function, you can run the following code:

pointA = (1, 6)
pointB = (7, 2)
print(getDist(pointA, pointB))

pointC = (2, 4, 9)
pointD = (0, -3, 6)
print(getDist(pointC, pointD))

You should get the following output:

7.21
7.87

Suggested Solution

Here’s the suggested solution for today’s practice question:

import math

def getDist(t1, t2):

    myMap = map(lambda x, y : (y-x)**2 , t1, t2)

    res = sum(myMap)
    res = math.sqrt(res)
    res = round(res, 2)
    
    return res

Here, we first import the math module on line 1 (in order to use the sqrt() function to calculate square root).

Next, we define the getDist() function with two paramters – t1 and t2 – from lines 3 to 11.

Inside the function, we use the map() function to apply the lambda function

lambda x, y : (y-x)**2

to t1 and t2.

This function accepts two inputs – x and y – and returns the square of their difference ((y-x)**2).

After applying the lambda function, we assign the resulting map object to a variable called myMap.

Next, we use the built-in sum() function to get the sum of all the items in myMap and assign the sum to a variable called res.

We then use the sqrt() function to get the square root of res (line 8) and round res off to two decimal places (line 9) using the round() function.

Finally, we return the value of res on line 11.

Written by Jamie | Last Updated November 6, 2020

Recent Posts