Exercise: Lambda Functions

Questions for: Lambda Functions

When is it appropriate to use a lambda function?
A:
For complex tasks requiring multiple expressions.
B:
When defining a function with a detailed docstring.
C:
For short, one-time tasks where a full function definition is not necessary.
D:
When implementing class methods.
Answer: C
Lambda functions are suitable for short-term, specific tasks where a full function definition is not needed, providing a concise way to express functionality.
What is the purpose of the functools.reduce() function when used with a lambda function?
A:
To apply the lambda function to each element of an iterable.
B:
To create a filter object based on the lambda function's condition.
C:
To accumulate values from an iterable using the lambda function.
D:
To sort the elements of an iterable using the lambda function.
Answer: C
The functools.reduce() function is used to successively apply the lambda function to the elements of an iterable, accumulating values.
How can a lambda function be used to define a key for sorting a list of tuples by the second element?
A:
lambda x: x[1]
B:
lambda x: x[0]
C:
lambda x: x[2]
D:
lambda x: x[-1]
Answer: A
The lambda function lambda x: x[1] extracts the second element of a tuple, which is suitable for sorting based on the second element.
How does the filter() function work when used with a lambda function?
A:
It creates a filter object based on the lambda function's condition.
B:
It sorts the elements of an iterable using the lambda function.
C:
It applies the lambda function to each element of an iterable.
D:
It accumulates values from an iterable using the lambda function.
Answer: A
The filter() function is used to create a filter object that includes only the elements from an iterable for which the lambda function returns True.
What is the primary advantage of using a lambda function over a regular function?
A:
Lambda functions support multiple expressions and statements.
B:
Lambda functions can be recursive.
C:
Lambda functions are more memory-efficient.
D:
Lambda functions are concise and can be written in a single line.
Answer: D
Lambda functions are often used for short, simple tasks due to their concise syntax, allowing them to be written in a single line.
Ad Slot (Above Pagination)
Quiz