1# mapping function
2def uppercase(u):
3 return str(u.upper())
4
5map_iterator = map(uppercase,['a','b','c'])
6mylist = list(map_iterator)
7print(mylist)
1# The map() function applies a given function
2# to each item of an iterable (list, tuple etc.) and returns an iterator
3
4numbers = [2, 4, 6, 8, 10]
5
6# returns square of a number
7def square(number):
8 return number * number
9
10# apply square() function to each item of the numbers list
11squared_numbers_iterator = map(square, numbers)
12
13# converting to list
14squared_numbers = list(squared_numbers_iterator)
15print(squared_numbers)
16
17# Output: [4, 16, 36, 64, 100]
1# Python program to demonstrate working
2# of map.
3
4# Return double of n
5def addition(n):
6 return n + n
7
8# We double all numbers using map()
9numbers = (1, 2, 3, 4)
10result = map(addition, numbers)
11print(list(result))
1def calculateSquare(n):
2 return n*n
3
4
5numbers = (1, 2, 3, 4)
6result = map(calculateSquare, numbers)
7print(result)
8
9# converting map object to set
10numbersSquare = list(result)
11print(numbersSquare)
1# Let's define general python function
2>>> def doubleOrNothing(num):
3... return num * 2
4
5# now use Map on it.
6>>> map(doubleOrNothing, [1,2,3,4,5])
7<map object at 0x7ff5b2bc7d00>
8
9# apply built-in list method on Map Object
10>>> list(map(doubleOrNothing, [1,2,3,4,5])
11[2, 4, 6, 8, 10]
12
13# using lambda function
14>>> list(map(lambda x: x*2, [1,2,3,4,5]))
15[2, 4, 6, 8, 10]
1numbers = [1, 2, 3, 4, 5]
2
3def square(num):
4 return num*num
5
6squares = list(map(square, numbers))
7print(squares)
8
9# Output
10# [1, 4, 9, 16, 25]