Exercise: Lambda Functions
Questions for: Lambda Functions
What does the following lambda function accomplish?
lambda x: x.capitalize() if isinstance(x, str) else None
A:
Capitalizes the first letter of a string and returns None for non-string values.
B:
Converts a string to uppercase and returns None for non-string values.
C:
Capitalizes the entire 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 capitalizes the first letter of a string and returns None for non-string values.
What is the purpose of the
functools.partial() function when used with a lambda function?
A:
To create a partial application of a lambda function.
B:
To create a filter object based on the lambda function's condition.
C:
To apply the lambda function to each element of an iterable.
D:
To sort the elements of an iterable using the lambda function.
Answer: A
functools.partial() is used to create a partial application of a function, including lambda functions, by fixing certain arguments.Discuss About this Question.
What is the output of the following code?
numbers = [1, 2, 3, 4, 5]
filtered = list(filter(lambda x: x % 2 != 0, numbers))
print(filtered)
A:
[1, 3, 5]B:
[2, 4]C:
[1, 2, 3, 4, 5]D:
[1, 4]
Answer: A
The
filter() function with the lambda filters out even numbers.Discuss About this Question.
What does the following lambda function accomplish?
lambda x: len(x) if isinstance(x, str) else None
A:
Returns the length of a string and None for non-string values.
B:
Filters out strings and returns None for non-string values.
C:
Doubles the length of a string and returns None for non-string values.
D:
Returns the square of the length of a string and None for non-string values.
Answer: A
The lambda function returns the length of a string and None for non-string values.
Discuss About this Question.
What is the purpose of the
zip() function when used with a lambda function?
A:
To combine two iterables into a single iterable of tuples.
B:
To filter elements from an iterable based on the lambda function's condition.
C:
To create a sorted list based on the lambda function's values.
D:
To apply the lambda function to each element of an iterable.
Answer: A
zip() combines two iterables into pairs, allowing the lambda function to operate on corresponding elements.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.