Passing multiple arguments to map() function in Python

In this article, we are going to discuss various ways to use the map function of Python. We will also go through some examples to understand even better.

first of all, what map does, the map will take two arguments

map(function, *iterators)

it will return map object address

and what it does is, it will take all the iterators and map to function arguments and return the value of return function.

Example 1:

Let’s say I have a million length iterator (ex: list) and I want to impose my custom function on every object in the list.

def custom_function(x):
  if x%2==0:
    return "even"
  return "odd"

myIterable = list(range(0,1000000,5))

so line 6 gives output like <mapx0x6623a4> which means that the return object of the map function is stored at that address. line 7 we cast the map into the list and printed.

Example 2:

This is the most used line during my journey of competitive programming and love to share it. In general, you are asked to take an array of space-separated integers as input. I use the map here.


Above what happens is, first we take the string as input which contains space-separated integers. Then we split it based on space so that we have a list. now we have characters. Then passed each object of iterable to int function for casting.

Example 3:

Here we discuss the meaning of *Iterable in the function definition. which means that we can pass any number of iterators. Let’s see a simple code of how it works.

The problem we have two lists namely first and second. We need to add them index wise.

def myadd(a,b):
  return a+b


This gives an output : [11,12,13] which is the addition of elements index wise. What happens is that the first element of the first list is mapped to a. Then b takes the first value in the second list. which are a=1,b=10. Then myadd function use these arguments and returns the value. likely it will continue till the end.

Final Example:

Let’s see one final example but a more sophisticated one. we are given three numbers to our function. The three numbers given to the function are side lengths and we have to tell whether it forms a triangle or not. I have thought of doing it in one line. so I’m using the lambda function.

print(list(map(lambda a,b,c: a+b>c and b+c>a and c+a>b,[3,8,1],[4,6,2],[5,10,3])))

the lambda function will take three integers and returns true if those are able to create a triangle. so the output is [True, True, False]

How it came:

first step: a=3,b=4,c=5. It will satisfy the three conditions of the triangle and returns true.

Second Step: a=8,b=6,c=10. It will satisfy the three conditions of the triangle and returns true.

Third Step: a = 1, b=2,c=3. since b+c<a it will return false.

Please feel free to comment down your doubts and thoughts.

Leave a Reply

Your email address will not be published. Required fields are marked *