Contents
Python map() Function
Python map() function applies given function to each element of the iterable and returns a map object. The map object itself is an iterable.
In this tutorial, we will learn the syntax of map() function, and how to use it in Python programs.
Syntax – map()
Following is the syntax of map() builtin function in Python.
map(function, iterables)
The first argument is a function. You can pass a regular Python Function or a Python Lambda function for this argument.
The second argument is an iterable. The iterable could be a Python List, Python Tuple, Python Set, etc.
map() function returns a Python map object.
You can convert Python map to list, Python map to tuple, etc.
Example 1: Python map()
Following program is a simple use case of using map() function. We shall pass a regular Python function and a list of numbers as arguments. The function, first argument, will compute the square of each number in the list, second argument.
Python Program
def square(n):
return n**2
x = map(square, [1, 2, 3, 4, 5, 6])
print(list(x))
Run Output
[1, 4, 9, 16, 25, 36]
Example 2: Python map() with Lambda Function
In this example, we shall pass a lambda function as first argument to the map() function.
Python Program
x = map(lambda n: n**2, [1, 2, 3, 4, 5, 6])
print(list(x))
Run Output
[1, 4, 9, 16, 25, 36]
Summary
In this tutorial of Python Examples, we learned how to use map() function to apply a specific function on each element of a given iterable.