By using map we can apply function to each item of any iterable
map(function,iterable)
function can be built in or user defined
iterable can be list, tuple , set etc.
Using built-in function
String function len returns length of a string.
my_list=['Alex','Ronald','John']
my_list1=map(len,my_list) # using built in function len
print(list(my_list1))
Output
[4, 6, 4]
Using user defined function
The function my_function will add 5 and return to each number it receives.
MATH=[20,30,40]
def my_function(n):
return n+5
my_list1=map(my_function,MATH)
print(list(my_list1))
Output
[25, 35, 45]
Using lambda with map()
Sometime our function may require one input parmeter.
MATH=[20,30,40]
def my_function(n):
return n+5
my_list1=map(lambda n:my_function(n),MATH)
print(list(my_list1))
Using Multiple iterators
We can get sum of three subjects
MATH=[20,30,40]
ENGLISH=[30,40,50]
SCIENCE=[40,50,60]
def my_function(a,b,c):
return a+b+c
my_list1=map(my_function,MATH,ENGLISH,SCIENCE)
print(list(my_list1))
Output
[90, 120, 150]
Creating string from list
Here before using join() we can convert all elements to string by using str. We will apply map() to all elements to convert them to string.
my_list=['You','have','to','pass','in',3,'languages']
my_str = ' #'.join(map(str,my_list)) # from list create string
print(my_str)
← Subscribe to our YouTube Channel here