Python Programming - Lambda Functions

Exercise : Lambda Functions - General Questions
  • Lambda Functions - General Questions
61.
What does the following lambda function accomplish?
lambda x: x.split()[0] if isinstance(x, str) else None
Extracts the first word of a string and returns None for non-string values.
Converts a string to uppercase and returns None for non-string values.
Joins all words in a string and returns None for non-string values.
Returns the length of a string and None for non-string values.
Answer: Option
Explanation:
The lambda function extracts the first word of a string and returns None for non-string values.

62.
What is the purpose of the all() function when used with a lambda function?
To check if any element in an iterable satisfies the lambda function's condition.
To check if all elements in an iterable satisfy the lambda function's condition.
To apply the lambda function to each element of an iterable.
To create a filter object based on the lambda function's condition.
Answer: Option
Explanation:
The all() function returns True if all elements in the iterable satisfy the lambda function's condition.

63.
What is the result of the following code?
items = ['apple', 'banana', 'cherry']
lengths = list(map(lambda x: len(x), items))
print(lengths)
[5, 6, 6]
[3, 6, 6]
[1, 1, 1]
['apple', 'banana', 'cherry']
Answer: Option
Explanation:
The map() function applies the lambda function to get the length of each string in the list.

64.
What is the output of the following code?
numbers = [1, 2, 3, 4, 5]
filtered = list(filter(lambda x: x > 3, numbers))
print(filtered)
[3, 4, 5]
[1, 2, 3]
[4, 5]
[1, 2, 3, 4, 5]
Answer: Option
Explanation:
The filter() function with the lambda filters out numbers less than or equal to 3.

65.
What is the primary purpose of using a lambda function with the functools.reduce() function?
To filter elements from an iterable.
To apply a transformation to each element of an iterable.
To apply the lambda function cumulatively to the items of an iterable.
To sort the elements of an iterable using the lambda function.
Answer: Option
Explanation:
The functools.reduce() function applies the lambda function cumulatively to the items of an iterable.