0
0
Pythonprogramming~20 mins

Lambda vs regular functions in Python - Practice Questions

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 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)
A[0, 2, 4]
B[4, 4, 4]
C[0, 0, 0]
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Think about how default arguments capture values at definition time.
โ“ Predict Output
intermediate
2:00remaining
Difference 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)
A[0, 2, 4]
B[4, 4, 4]
C[0, 0, 0]
DNameError
Attempts:
2 left
๐Ÿ’ก Hint
Consider when the variable i is looked up inside the function.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify 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?
Alambda x, y: (print('Adding'), x + y)[1]
Blambda x, y: print('Adding') + (x + y)
Clambda x, y: {print('Adding'); return x + y}
Dlambda x, y: x + y; print('Adding')
Attempts:
2 left
๐Ÿ’ก Hint
Remember lambdas can only have expressions, not statements.
โ“ Predict Output
advanced
2:00remaining
Output 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)
A[0, 1, 2]
B[0, 0, 0]
C[2, 2, 2]
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Think about when the variable i is evaluated inside the lambda.
๐Ÿง  Conceptual
expert
2:00remaining
Why use lambda instead of regular function?
Which of these is the best reason to use a lambda function instead of a regular function?
ATo create functions that can be called without parentheses
BTo improve performance by compiling faster than regular functions
CTo allow multiple statements inside the function body
DTo define a small anonymous function inline, especially as an argument to another function
Attempts:
2 left
๐Ÿ’ก Hint
Think about where lambdas are often used in Python code.