squares)
Note that we are not required to create a separate function to calculate the square of a number.
List of squares: [1, 4, 9, 16, 25]
Till now we only looked at
map()with argument function taking only one parameter. But we may also need to supply multiple parameters to it.
Remember that we need to supply equal number of iterables as the number of parameters expected by the function.
Below is an example that adds elements of two lists and assigns them to a third list.
# Function to add two numbers def add(num1, num2): return num1+num2 list1 = [1,2,3,4,5] list2 = [6,7,8,9,10] sum = list(map(add, list1, list2)) print('List one:', list1) print('List two:', list2) print('Sum of lists:', sum)
Note that in this example, the function takes two arguments and there are an equal number of lists.
map() iterates over all the iterables, takes a value from all of these and passes them to the function.
Above code written using a lambda function is given below.
list1 = [1,2,3,4,5] list2 = [6,7,8,9,10] sum = list(map(lambda x,y: x+y, list1, list2)) print('List one:', list1) print('List two:', list2) print('sum of lists:', sum)
Now there is no need to define a separate function to add two numbers as lambda function does this inline.