Python map() Function
The Python map() function is used to return a object list containing mapped elements of the specified iterable using specified mapping function. An iterable can be any data structure like list, tuple, set, string and dictionary etc. Along with this, a range() function can also be used as an iterable.
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 below example, map() function is used to return 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 below example, map() function is used to return 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 below example, map() function is used to return 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