Exercise: Lambda Functions

Questions for: Lambda Functions

What is the output of the following code?
items = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 3, items))
A:
[1, 2, 3, 4, 5]
B:
[3, 6, 9, 12, 15]
C:
[1, 4, 9, 16, 25]
D:
[1, 2, 3]
Answer: B
The map() function applies the lambda function to multiply each item by 3.
What does the following lambda function do?
lambda x: x if x % 2 == 0 else None
A:
Doubles even numbers and returns None for odd numbers.
B:
Filters out even numbers and returns None for odd numbers.
C:
Doubles even numbers and returns the original value for odd numbers.
D:
Returns the square of even numbers and None for odd numbers.
Answer: B
The lambda function filters out even numbers by returning None for them.
Which built-in function can be used with a lambda function to find the sum of values in an iterable?
A:
sum()
B:
max()
C:
len()
D:
filter()
Answer: A
The sum() function can be used with a lambda function to find the sum of values in an iterable based on the lambda function's criteria.
When using the sorted() function with a lambda function to sort a list of strings, how can the sorting be case-insensitive?
A:
Use the case_insensitive=True parameter.
B:
Use the lower() method inside the lambda function.
C:
Use the sorted(case_insensitive=True) syntax.
D:
It is not possible to achieve case-insensitive sorting with lambda functions.
Answer: B
Using lower() inside the lambda function converts strings to lowercase, achieving case-insensitive sorting.
What does the following lambda function accomplish?
lambda x: x.upper()
A:
Converts a string to lowercase.
B:
Converts a string to uppercase.
C:
Reverses a string.
D:
Trims leading and trailing whitespaces from a string.
Answer: B
The lambda function lambda x: x.upper() converts a string to uppercase.
Ad Slot (Above Pagination)
Quiz