0
0
Pythonprogramming~20 mins

Why lambda functions are used in Python - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Lambda Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of a lambda function used with map
What is the output of this code that uses a lambda function with map to double numbers?
Python
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
A[1, 4, 9, 16]
B[1, 2, 3, 4]
C[2, 4, 6, 8]
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Think about what the lambda function does to each number in the list.
๐Ÿง  Conceptual
intermediate
1:30remaining
Why use lambda functions instead of regular functions?
Which of the following best explains why lambda functions are used in Python?
AThey run faster than regular functions.
BThey allow creating small anonymous functions quickly without naming them.
CThey can only be used once and then disappear.
DThey automatically optimize code for better memory usage.
Attempts:
2 left
๐Ÿ’ก Hint
Think about the difference between naming a function and using a quick inline function.
โ“ Predict Output
advanced
2:00remaining
Output of sorting with a lambda key
What is the output of this code that sorts a list of tuples by the second item using a lambda function?
Python
pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
pairs.sort(key=lambda x: x[1])
print(pairs)
A[(2, 'a'), (1, 'b'), (3, 'c')]
B[(1, 'b'), (2, 'a'), (3, 'c')]
C[(3, 'c'), (1, 'b'), (2, 'a')]
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
The lambda function picks the second element of each tuple for sorting.
๐Ÿ”ง Debug
advanced
1:30remaining
Identify the error in lambda usage
What error does this code raise and why?
Python
func = lambda x, y: x + y
print(func(2))
ATypeError: missing 1 required positional argument 'y'
BSyntaxError: invalid syntax
CNameError: name 'func' is not defined
DNo error, output is 2
Attempts:
2 left
๐Ÿ’ก Hint
Check how many arguments the lambda expects and how many are given.
๐Ÿš€ Application
expert
2:30remaining
Using lambda to filter and transform a list
Which option produces the list of squares of even numbers from 0 to 9 using lambda functions?
Alist(filter(lambda x: x % 2 == 0, map(lambda x: x**2, range(10))))
Blist(filter(lambda x: x**2, map(lambda x: x % 2 == 0, range(10))))
Clist(map(lambda x: x % 2 == 0, filter(lambda x: x**2, range(10))))
Dlist(map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(10))))
Attempts:
2 left
๐Ÿ’ก Hint
First select even numbers, then square them.