Python map() Function


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 of map()

Following is the syntax of map() builtin function in Python.

map(function, iterables)

where

ParameterDescription
functionA function. You can pass a regular Python Function or a Python Lambda function for this argument.
iterablesAn iterable. The iterable could be a Python List, Python Tuple, Python Set, etc.

The function returns a Python map object.

Examples

1. Create a map

The 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))

Output

[1, 4, 9, 16, 25, 36]

2. Map using 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))

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.