map() function in python by R4R Team

-map() is a python function which returns a list of the results after applying the given function to each item of a given iterable like list,tuple.

Syntax-

map(fun,iter)

-Here fun is a function and iter is iterable.
-It return the list.

Example-

map(int,['1','2','3'])
it will return the [1,2,3]

-because we have a numeric string in the list, so why using map we convert this into integer number.


program-

#list of numeric string to integer number
a=map(int,['1','2','3','4'])
print(list(a))

#float to integer mapping
a=map(int,[2.34,1.2,6.7,3.1])
print(list(a))

def square(n):
return n**2
#square the list
l=[1,2,3,4,5]
print("List is",l)
print("After Square of number,list is")
print(list((map(square,l))))

#square the tuple
t=tuple([3,5,6,8,1])
print("Tuple is",t)
print("After Square of number,Tuple is")
print(list((map(square,t))))


output-

[1, 2, 3, 4]
[2, 1, 6, 3]
List is [1, 2, 3, 4, 5]
After Square of number,list is
[1, 4, 9, 16, 25]
Tuple is (3, 5, 6, 8, 1)
After Square of number,Tuple is
[9, 25, 36, 64, 1]


-In this program, we do four mapping, first mapping is to numeric string to integer by 'int' function, second is of float to integer, third is sqaure of list items and similarly square of tuple items.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!