Challenge - 5 Problems
Lambda Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediateOutput of lambda with default argument
What is the output of this code?
Python
funcs = [(lambda x=i: x*2) for i in range(3)] results = [f() for f in funcs] print(results)
Attempts:
2 left
๐ก Hint
Think about how default arguments capture values at definition time.
โ Incorrect
Each lambda captures the current value of i as a default argument, so calling each lambda returns double its own i value.
โ Predict Output
intermediateDifference in output between lambda and regular function
What is the output of this code?
Python
def make_funcs(): funcs = [] for i in range(3): def f(): return i * 2 funcs.append(f) return funcs funcs = make_funcs() results = [f() for f in funcs] print(results)
Attempts:
2 left
๐ก Hint
Consider when the variable i is looked up inside the function.
โ Incorrect
The inner function f uses the variable i from the outer scope, which after the loop ends is 2. So all functions return 2*2=4.
๐ง Debug
advancedIdentify the error in lambda with multiple statements
Which option shows the correct way to write a lambda that returns the sum of two numbers and prints a message?
Attempts:
2 left
๐ก Hint
Remember lambdas can only have expressions, not statements.
โ Incorrect
Option A uses a tuple expression to execute print and then return the sum. Other options have syntax errors or invalid syntax for lambdas.
โ Predict Output
advancedOutput of lambda capturing loop variable without default
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
Think about when the variable i is evaluated inside the lambda.
โ Incorrect
All lambdas refer to the same variable i, which after the loop ends is 2, so all return 2.
๐ง Conceptual
expertWhy use lambda instead of regular function?
Which of these is the best reason to use a lambda function instead of a regular function?
Attempts:
2 left
๐ก Hint
Think about where lambdas are often used in Python code.
โ Incorrect
Lambdas are used for small, unnamed functions, often passed as arguments. They cannot contain multiple statements and do not improve performance.
