Python map()
____________________________________________
The map() function applies a given function to each item of an
iterable (list, tuple etc.) and returns a list of the results.
The syntax of map() is:
map(function, iterable, ...)
map() Parameter
function - map() passes each item of the iterable to this function.
iterable -iterable which is to be mapped
You can pass more than one iterable to the map() function.
Return Value from map()
The map() function applies a given to function to each item of an
iterable and returns a list of the results.
The returned value from map() (map object) then can be passed
to functions like list() (to create a list), set() (to create a set) and
so on.
Example 1: How map() works?
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
When you run the program, the output will be:
<map object at 0x7f722da129e8>
{16, 1, 4, 9}
In the above example, each item of the tuple is squared.
Since map() expects a function to be passed in, lambda functions
are commonly used while working with map() functions.
A lambda function is a function without a name. Visit this page to
learn more about Python lambda Function.
Example 2: How to use lambda function with map()?
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
When you run the program, the output will be:
<map 0x7fafc21ccb00>
{16, 1, 4, 9}
There is no difference in functionalities of this example and Example 1.
Example 3: Passing Multiple Iterators to map() Using Lambda
In this example, corresponding items of two lists are added.
Program:
num1 = [4, 5, 6]
num2 = [5, 6, 7]
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))
When you run the program, the output will be:
[9, 11, 13]