Explain : map() Function.
Answers
map() Function :-
- The map function takes two arguments: a function and a sequence such as a list.
- This function makes an iterator that applies the function to each element of a sequence.
- We can pass lambda function to this map function without even naming it.
- In this case, we refer to lambda functions as an anonymous function.
In the following example, we create a list nums consisting of numbers and pass it to a map function along with the lambda function which will square each element of the list :
# Creating a list of all numbers
nums = [1, 2, 3, 4, 5]
# Defining a lambda function to square each number and
# passing it as an argument to map function
squares = map(lambda num: num ** 2, nums)
The lambda function in the above example will square each element of the list and the map function will map each output to the corresponding elements in the original list. We then store the result into a variable called
. If we print the square variable, Python will reveal us that it is a map object.
# Printing squares
print(squares)
# Output
<map object at 0x00000000074EAD68>
• To see what this object contains, we need to cast it to list using the list function as shown below :
# Casting map object squares to a list and printing it
print(list(squares))
# Output
[1, 4, 9, 16, 25]
map() Function :-
The map function takes two arguments: a function and a sequence such as a list.
This function makes an iterator that applies the function to each element of a sequence.
We can pass lambda function to this map function without even naming it.
In this case, we refer to lambda functions as an anonymous function.
In the following example, we create a list nums consisting of numbers and pass it to a map function along with the lambda function which will square each element of the list :
# Creating a list of all numbers
nums = [1, 2, 3, 4, 5]
# Defining a lambda function to square each number and
# passing it as an argument to map function
squares = map(lambda num: num ** 2, nums)
The lambda function in the above example will square each element of the list and the map function will map each output to the corresponding elements in the original list. We then store the result into a variable called . If we print the square variable, Python will reveal us that it is a map object.
# Printing squares
print(squares)
# Output
<map object at 0x00000000074EAD68>
• To see what this object contains, we need to cast it to list using the list function as shown below :
# Casting map object squares to a list and printing it
print(list(squares))
# Output
[1, 4, 9, 16, 25]