Python Map function code example

Example 1: mapping in python string

# mapping function
def uppercase(u):
    return str(u.upper())

map_iterator = map(uppercase,['a','b','c'])
mylist = list(map_iterator)
print(mylist)

Example 2: map in python 3

map(function, iterable, ...)

Example 3: map function in python

# 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))

Example 4: map in python

'''try this instead of defining a function'''

a = [1,2,3,4]
a = list(map(lambda n: n+n, a))

print(a)

Example 5: python dictionary map function

dictionary = {k: f(v) for k, v in dictionary.items()}

Example 6: Python Map function

# 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]