Exercise: Lambda Functions
Questions for: Lambda Functions
What does the following lambda function accomplish?
lambda x: x.split()[0] if isinstance(x, str) else None
A:
Extracts the first word of a string and returns None for non-string values.
B:
Converts a string to uppercase and returns None for non-string values.
C:
Joins all words in 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 extracts the first word of a string and returns None for non-string values.
When using the
sorted() function with a lambda function to sort a list of tuples, how can you sort based on the second element of each tuple?
A:
sorted(tuples, key=lambda x: x[1])
B:
sorted(tuples, sort_key=lambda x: x[1])
C:
sorted(tuples, key=tuple[1])
D:
sorted(tuples, sort_key=tuple[1])
Answer: A
The
key parameter is used to specify the lambda function that extracts the second element for sorting.Discuss About this Question.
What does the following lambda function do?
lambda x, y: x + y
A:
Concatenates two strings.
B:
Multiplies two numbers.
C:
Adds two numbers.
D:
Raises one number to the power of another.
Answer: C
The lambda function adds two numbers.
Discuss About this Question.
What is the purpose of the
reduce() function when used with a lambda function?
A:
To filter elements from an iterable based on the lambda function's condition.
B:
To create a sorted list based on the lambda function's values.
C:
To apply the lambda function cumulatively to the items of an iterable.
D:
To combine two iterables into a single iterable of tuples.
Answer: C
The
reduce() function is used to apply the lambda function cumulatively to the items of an iterable.Discuss About this Question.
How can a lambda function be used with the
min() function to find the minimum length string in a list of strings?
A:
min(strings, key=len)
B:
min(strings, lambda x: x)
C:
min(strings, lambda x: len(x))
D:
min(strings, key=lambda x: x)
Answer: A
The
key parameter is used to specify the lambda function that calculates the length of each string.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.