xxxxxxxxxx
# 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']]
xxxxxxxxxx
# 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]
xxxxxxxxxx
# 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))
xxxxxxxxxx
#Methodmap will make your code more readable
#We multiply all the values in the list by two
numbers=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(map(lambda num: num*2, numbers)))
#If you run the code, you will see that you were able to do this without using a loop
#GOOD LUCK
xxxxxxxxxx
# 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]
xxxxxxxxxx
# 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))
# result [2, 4, 6, 8]
xxxxxxxxxx
#### Core python use case #####
#map(func_name, some_list)
items = [1, 2, 3, 4]
list(map(lambda x: x + 2 , items)) ## [3, 4, 5, 6]
#### Dataframe Application #####
# Method 1
df["col"].apply(lambda x: x+1)
# Method 2
genders = {'James': 'Male', 'Jane': 'Female'}
df['gender'] = df['name'].map(genders)
xxxxxxxxxx
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)