educative.io

Function as argument using lambda

Please Explain me Line no.3

def calculator (operation, n1, n2):
   return operation(n1, n2) 
result = calculator(lambda n1, n2 : n1 * n2, 10, 20) 
print (result)
print (calculator(lambda n1, n2 : n1 + n2, 10, 20))

This is Waleed from Educative. Thank you for reaching out to us!

On line 3, we are calling the calculator function with three arguments.

  1. The first argument is a lambda with:

    • parameters n1 and n2 .
    • the expression n1 * n2.
  2. 10 is the second argument.

  3. 20 is the third argument.

The operation parameter is a function takes the Lambda lambda n1, n2 : n1 * n2 as the first argument on line 3.

Lambda computes the value of n1 * n2 based on the second and third arguments of the calculator function and returns the computed value.

Best Regards,
Waleed Khalid | Developer Advocate
Educative

1 Like

Please explain me line number 2

This is Waleed from Educative. Thank you for reaching out to us!

On line 2, we are calling the function operation with n1 and n2 as input arguments and returning its value.

operation is a lambda that needs to be defined as the first argument whenever we call the calculator function.

Best Regards,
Waleed Khalid | Developer Advocate
Educative

Hi could you explain me why do we need to convert in a list when we use filter() or map()
i.e:
greater_than_10 = list(filter(lambda n: n > 10, numList))
print(list(double_list))

In Python 3, filter and map return an iterable object. Such an object cannot be printed directly. Try printing it and it’ll just show the address and type of the object. By converting it into a list we can print its content.

However, if you are familiar with for loops, the elements of an iterable can be accessed (or iterated) by using a loop such as:

for num in greater_than_10:
    print(num)
    do something else with num

Can u create a function that doubles a number and use it in map()