Challenge - 5 Problems
Lambda Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of a simple lambda function
What is the output of this Python code?
Python
func = lambda x: x * 3 result = func(4) print(result)
Attempts:
2 left
๐ก Hint
Remember that lambda functions return the expression result.
โ Incorrect
The lambda multiplies the input by 3. Input is 4, so 4 * 3 = 12.
โ Predict Output
intermediate2:00remaining
Lambda with multiple arguments
What will this code print?
Python
adder = lambda a, b: a + b print(adder(5, 10))
Attempts:
2 left
๐ก Hint
The lambda adds two numbers.
โ Incorrect
The lambda adds 5 and 10, resulting in 15.
โ Predict Output
advanced2:30remaining
Lambda capturing variable in loop
What is the output of this code?
Python
funcs = [] for i in range(3): funcs.append(lambda: i) results = [f() for f in funcs] print(results)
Attempts:
2 left
๐ก Hint
Lambdas capture variables by reference, not by value.
โ Incorrect
All lambdas capture the same variable i, which ends at 2 after the loop.
โ Predict Output
advanced2:30remaining
Correct lambda capturing loop variable
What does this code print?
Python
funcs = [] for i in range(3): funcs.append(lambda i=i: i) results = [f() for f in funcs] print(results)
Attempts:
2 left
๐ก Hint
Default arguments capture the current value at each loop iteration.
โ Incorrect
Using default argument i=i captures the current value of i for each lambda.
๐ง Conceptual
expert3:00remaining
Behavior of lambda with mutable default argument
Consider this code snippet. What will be printed?
Python
def make_funcs(): funcs = [] lst = [] for i in range(3): lst.append(i) funcs.append(lambda x=lst: x) return funcs funcs = make_funcs() for f in funcs: print(f())
Attempts:
2 left
๐ก Hint
Default arguments are evaluated once when the function is defined.
โ Incorrect
The default argument x=lst captures the same list object, which has all elements at the end.