Python map function is used to execute a function on all elements of an iterator. The function to execute will be passed to map() as a parameter. Through this blog post, we will understand map() function via many examples in coding.

A Quick Example:

def newfunc(val):
    return val * 2

result = map(newfunc, [1, 2, 3, 4])
print(list(result))

/* Result: [2, 4, 6, 8] */
Python map function likes a short hand of a loop
Lambda function likes a short hand of a loop.
(London – Source: Wallpapers Wide)

Definition and Usage

In python, map function syntax is quite simple:

map(function, iterators)
  • function: Required and will execute for items of iterators
  • iterators: Required. You can send many iterators. However, the function must have one parameter for each iterator.

Python Map Examples

Example 1: How to use lambda function with map()

In the above example, we can make it shorter, cleaner with a lambda function.

result = map(lambda x: x * 2, [1, 2, 3, 4])
print(list(result))

/* Result: [2, 4, 6, 8] */

If you are new to Python, you should read this article for more detail of lambda function (What is lambda function?)

Example 2: Passing multiple Iterators to map() function

Lambda function should have one parameter for each iterator.

iter1 = [1, 5, 7]
iter2 = [9, 5, 3]

result = map(lambda x, y: x + y, iter1, iter2)
print(list(result))

/* Result: [10, 10, 10] */

Example 3: Passing multiple Iterators with different size

Let's see what happen if we pass multiple iterators with different size.

In python 2, we got an exception. Therefore, be aware of this case in your code.

iter1 = [1, 5, 7, 9, 8]
iter2 = [9, 5, 3]

result = map(lambda x, y: x + y, iter1, iter2)
print(list(result))

/* Result:

Traceback (most recent call last):
  File "main.py", line 6, in 
    result = map(lambda x, y: x + y, iter2, iter1)
  File "main.py", line 6, in 
    result = map(lambda x, y: x + y, iter2, iter1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

*/

In python 3, we get a map object with the size of smallest iterator

iter1 = [1, 5, 7, 9, 8]
iter2 = [9, 5, 3]

result = map(lambda x, y: x + y, iter1, iter2)
print(list(result))

/* Result: [10, 10, 10] */

References

In this post, I provided some simple examples for python map function. However, you can get more details from these links:

 

Sharing is caring!

2 thoughts on “Python Map Function

Leave a Reply

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

Name *