# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
# Output :-
# 1 + 1 = 2 / 2 + 2 = 4 / 3 + 3 = 6 / 4 + 4 = 8
[2, 4, 6, 8]
# Example With Strings :-
# List of strings
my_list = ['sat', 'bat', 'cat', 'mat']
# map() can listify the list of strings individually
test = list(map(list, my_list))
print(test)
# Output :-
# listify the list of strings individually Like :-
# 'sat' 3 Letters ==> The Function is Offered Individually :- 's', 'a', 't'
[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
# The map function applies a function to every item in a list,
# and returns a new list.
numbers = [0, -1, 2, 3, -4]
def square_func(n):
return n*n
new_numbers = list(map(square_func, numbers))
#new_numbers: [0, 1, 4, 9, 16]
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
# Let's define general python function
>>> def doubleOrNothing(num):
... return num * 2
# now use Map on it.
>>> map(doubleOrNothing, [1,2,3,4,5])
<map object at 0x7ff5b2bc7d00>
# apply built-in list method on Map Object
>>> list(map(doubleOrNothing, [1,2,3,4,5])
[2, 4, 6, 8, 10]
# using lambda function
>>> list(map(lambda x: x*2, [1,2,3,4,5]))
[2, 4, 6, 8, 10]
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = addition(numbers)
print(list(result))
#The map function is used to do a certain function to a certain iterable
#It takes a function and an iterable
numbers = [1,2,3,4,5,6,7,8,9,10]
x = map(lambda nom : nom*nom, numbers)
print(list(x))
#So here my function is the lambda and the iterable is the numbers list
#And with this I apply nom*nom to every item to the list
# if I didn't put the list function before x it would print map object at .....