0
0
Pythonprogramming~20 mins

Lambda syntax and behavior in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Lambda Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A12
B7
CError
DNone
Attempts:
2 left
๐Ÿ’ก Hint
Remember that lambda functions return the expression result.
โ“ Predict Output
intermediate
2:00remaining
Lambda with multiple arguments
What will this code print?
Python
adder = lambda a, b: a + b
print(adder(5, 10))
A15
B510
CTypeError
DNone
Attempts:
2 left
๐Ÿ’ก Hint
The lambda adds two numbers.
โ“ Predict Output
advanced
2: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)
A[0, 1, 2]
B[2, 2, 2]
C[0, 0, 0]
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Lambdas capture variables by reference, not by value.
โ“ Predict Output
advanced
2: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)
A[0, 0, 0]
B[2, 2, 2]
C[0, 1, 2]
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Default arguments capture the current value at each loop iteration.
๐Ÿง  Conceptual
expert
3: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())
ATypeError
B
[0]
[0, 1]
[0, 1, 2]
C
[]
[]
[]
D
[0, 1, 2]
[0, 1, 2]
[0, 1, 2]
Attempts:
2 left
๐Ÿ’ก Hint
Default arguments are evaluated once when the function is defined.