Exercise: Lambda Functions

Questions for: Lambda Functions

In Python, what does the following code represent?
lambda x: x ** 2
A:
A lambda function squaring its input
B:
A lambda function with two parameters
C:
A lambda function taking the square root of its input
D:
A lambda function doubling its input
Answer: A
The lambda function lambda x: x ** 2 represents a function that squares its input (multiplies it by itself).
Which of the following is a valid reason for using a regular function instead of a lambda function?
A:
When defining a function for a short, one-time task
B:
When the function requires multiple expressions or statements
C:
When the function is passed as an argument to map()
D:
When the function is used for filtering elements based on a condition
Answer: B
Regular functions are more suitable when complex logic, multiple expressions, or statements are needed, as they can span multiple lines of code.
What is the purpose of the any() function when used with a lambda function?
A:
To apply the lambda function to each element of an iterable
B:
To check if any element in an iterable satisfies the lambda function's condition
C:
To create a filter based on the lambda function's condition
D:
To map the lambda function to each element of an iterable
Answer: B
The any() function returns True if at least one element in the iterable satisfies the condition specified by the lambda function.
How does the scope of variables work in lambda functions?
A:
Lambda functions can only access global variables
B:
Lambda functions have their own local scope
C:
Lambda functions can access variables from the calling environment
D:
Lambda functions cannot access any variables
Answer: C
Lambda functions can access variables from the surrounding environment, making them useful for short, specific tasks.
What happens if a lambda function is used as an argument for the key parameter in the max() function?
A:
It raises a SyntaxError
B:
It serves as the comparison function for finding the maximum value
C:
It must be enclosed in square brackets
D:
It only works if the lambda function has a single parameter
Answer: B
When a lambda function is used as the key parameter in max(), it defines the sorting criteria for finding the maximum value.
Ad Slot (Above Pagination)
Quiz