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]
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 \<module\> result = map(lambda x, y: x + y, iter2, iter1) File "main.py", line 6, in \<lambda\> 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 of the python map function. However, you can get more details from these links:
The post Python Map Function appeared first on Python Geeks.
Top comments (5)
Very cute! The first example also made me realise that
map
,filter
, and the likes, that work on iterables, are lazy.repl.it example
Awesome! It's an interesting thing that I haven't known yet. Thanks a lot for your sharing.
Btw, Don't you mind if I share your example in the original post? It will help other developers more understand map and filter.
Also, notice that my code example has syntax highlighting.
This is because I use
Instead of
Thanks for the notice. It helps me a lot. :)
I most certainly don't mind :)