Skip to content

Question 24

Given the following function definition:

def foo(a):
    return a + 2

Which lambda expression is equivalent to calling foo(9)?

Hint

The lambda function should be input agnostic the same way foo(a) is input agnostic with respect to the value of parameter a.

Format of a lambda function: lambda <input params> : <returned expression>

Solution

Basically, we need to find a lambda function that can represent just the name foo from foo(9), which should look something like: <lambda function>(9).

Format of a lambda function: lambda <input params> : <returned expression>

foo() takes in 1 input parameter a, and returns the result of a + 2. Substitute them accordingly to get: lambda a: a + 2. This alone is our lambda function equivalent, but not yet the equivalent representation of foo(9), where you specifically define a = 9 into said function.

(lambda a: a + 2)(9) is the exact equivalent of foo(9).

Answer
(lambda a: a + 2)(9)