The map()
function executes a given function to each element of an iterable (such as lists, tuples, etc.).
Example
numbers = [2, 4, 6, 8, 10]
# returns the square of a number
def square(number):
return number * number
# apply square() to each item of the numbers list
squared_numbers = map(square, numbers)
# converting to list for printing
result = list(squared_numbers)
print(result) # Output: [4, 16, 36, 64, 100]
map() Syntax
Its syntax is:
map(function, iterables)
map() Arguments
The map()
function takes two arguments:
- function - a function that is applied to each element of the iterables
- iterables - iterables such as lists, tuples, etc
Note: We can pass more than one iterable to the map()
function.
map() Return Value
The map()
function returns a map object, which can be easily converted to lists, tuples, etc.
Example 1: Working of map()
def square(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(square, numbers)
print(result)
# converting the map object to set
result = set(result)
print(result)
Output
<map object at 0x7f722da129e8> {16, 1, 4, 9}
In the above example, each item of the tuple is squared and then converted to a set.
Example 2: map() with Lambda
In a map()
function, we can also use a lambda function instead of a regular function. For example,
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
# convert to set and print it
print(set(result))
Output
<map 0x7fafc21ccb00> {16, 1, 4, 9}
There is no difference in functionalities of this example and Example 1.
Example 3: map()
In this example, we have passed two iterables to the map()
function.
num1 = [1, 2, 3]
num2 = [10, 20, 40]
# add corresponding items from the num1 and num2 lists
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))
Output
[11, 22, 43]