Exercise: Lambda Functions

Questions for: Lambda Functions

What does the following lambda function do?
lambda x: x.lower() if isinstance(x, str) else None
A:
Converts a string to lowercase and returns None for non-string values.
B:
Converts a string to uppercase and returns None for non-string values.
C:
Capitalizes the first letter of a string and returns None for non-string values.
D:
Returns the length of a string and None for non-string values.
Answer: A
The lambda function converts a string to lowercase and returns None for non-string values.
What is the primary purpose of using a lambda function with the functools.reduce() function?
A:
To filter elements from an iterable.
B:
To apply a transformation to each element of an iterable.
C:
To apply the lambda function cumulatively to the items of an iterable.
D:
To sort the elements of an iterable using the lambda function.
Answer: C
The functools.reduce() function applies the lambda function cumulatively to the items of an iterable.
What is the output of the following code?
numbers = [1, 2, 3, 4, 5]
filtered = list(filter(lambda x: x > 3, numbers))
print(filtered)
A:
[3, 4, 5]
B:
[1, 2, 3]
C:
[4, 5]
D:
[1, 2, 3, 4, 5]
Answer: C
The filter() function with the lambda filters out numbers less than or equal to 3.
What is the result of the following code?
items = ['apple', 'banana', 'cherry']
lengths = list(map(lambda x: len(x), items))
print(lengths)
A:
[5, 6, 6]
B:
[3, 6, 6]
C:
[1, 1, 1]
D:
['apple', 'banana', 'cherry']
Answer: A
The map() function applies the lambda function to get the length of each string in the list.
What is the purpose of the all() function when used with a lambda function?
A:
To check if any element in an iterable satisfies the lambda function's condition.
B:
To check if all elements in an iterable satisfy the lambda function's condition.
C:
To apply the lambda function to each element of an iterable.
D:
To create a filter object based on the lambda function's condition.
Answer: B
The all() function returns True if all elements in the iterable satisfy the lambda function's condition.
Ad Slot (Above Pagination)
Quiz