Python Tutorial Python Advanced Python References Python Libraries

Python map() Function



The Python map() function returns a object list containing mapped elements of the specified iterable using specified mapping function. An iterable can be any data structure list, tuple, set, string, dictionary and range iterables etc.

Syntax

map(function, iterable)

Parameters

function Required. function to map elements of iterable
iterable Required. iterable object like list, tuple, set, string , dictionary and range() etc.

Example: map() for squared number

In the example below, map() function returns a list containing elements of a given list mapped to its square.

def MyFunc(x):
    return x*x

MyList = [1, 3, 5, 6, 8, 9]
 
NewList = list(map(MyFunc, MyList))
print(NewList)

The output of the above code will be:

[1, 9, 25, 36, 64, 81]

Example: map() when multiple iterables

In the example below, map() function returns a list containing elements which are sum of elements of two given iterables.

def MyFunc(x, y):
    return x + y

MyList = [1, 3, 5, 6, 8, 9]
MyTuple = (10, 30, 50, 60, 80, 90)
 
NewList = list(map(MyFunc, MyList, MyTuple))
print(NewList)

The output of the above code will be:

[11, 33, 55, 66, 88, 99]

Example: using lambda function with map function

In the example below, map() function returns a list containing elements of a given tuple mapped to its square.

MyTuple = (1, 3, 5, 6, 8, 9)

NewList = list(map(lambda x: x*x , MyTuple))
print(NewList)

The output of the above code will be:

[1, 9, 25, 36, 64, 81]

❮ Python Built-in Functions