Python map() function

Python map applies given function to each element in iterable and returns the list.


Syntax


Return

It returns list after applying function on each of the element of iterable.


Example

Let’s see a simple example:

def doubleIt(num): return 2*num l=[1,2,3,4] # Will print map object print(map(doubleIt,l)) #Convert map to list using list() function ls=list(map(doubleIt,l)) print(ls)

Output:

[2, 4, 6, 8]

You can use lambda expression for the same.


Map using Lambda expressions

If you want to unzip tuple, you can use * with zip.Please refer below example.

def doubleIt(num): return 2*num l=[1,2,3,4] ls=list(map(lambda x:doubleIt(x),l)) print(ls)

Output:

[2, 4, 6, 8]

Map function in case of multiple iterators of same length

If iterables are of same length, then function should take that number of iterable as arguments and you will get same number of elements in output as the length of input iterators

l1=[1,2,3,4] l2=[5,6,7,8] def sumList(l1,l2): return l1+l2 ls=list(map(lambda x,y:sumList(x,y),l1,l2)) print(ls)

Output:

[6, 8, 10, 12]

Map function in case of multiple iterators of different length

If iterables are of different length, then function should take that number of iterable as arguments and you will get shortest iterable length as number of elements in output.

l1=[1,2,3,4] l2=[5,6,7] def multiplyList(l1,l2): return l1*l2 ls=list(map(lambda x,y:multiplyList(x,y),l1,l2)) print(ls)

Output:

[5, 12, 21]

That’s all about Python map function.

Leave a Reply

Your email address will not be published. Required fields are marked *