Exercise: Python

Questions for: Lambda Functions

What is the output of the following code?
items = ['apple', 'banana', 'cherry']
filtered = list(filter(lambda x: 'a' in x, items))
print(filtered)
A:
['apple', 'banana', 'cherry']
B:
['apple', 'banana']
C:
['apple']
D:
['banana']
Answer: B
The filter() function with the lambda filters items containing the letter 'a'.
What is the result of the following code?
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2 if x % 2 == 0 else x, numbers))
print(squared)
A:
[1, 4, 3, 16, 5]
B:
[1, 4, 9, 16, 25]
C:
[1, 2, 3, 4, 5]
D:
[1, 2, 9, 4, 25]
Answer: A
The lambda function squares even numbers and leaves odd numbers unchanged.
What is the purpose of the functools.lru_cache() function when used with a lambda function?
A:
To create a memoized version of the lambda function.
B:
To create a filter object based on the lambda function's condition.
C:
To sort the elements of an iterable using the lambda function.
D:
To apply the lambda function to each element of an iterable.
Answer: A
functools.lru_cache() is used to create a memoized version of a function, including lambda functions, for efficient caching of results.
When using the sorted() function with a lambda function to sort a list of dictionaries, how can you sort based on a specific key within each dictionary?
A:
sorted(dictionaries, lambda x: x['key'])
B:
sorted(dictionaries, key=lambda x: x['key'])
C:
sorted(dictionaries, sort_key=lambda x: x['key'])
D:
sorted(dictionaries, key='key')
Answer: B
The key parameter is used to specify the lambda function that extracts the specific key for sorting.
In Python, how can a lambda function be used with the max() function to find the maximum length string in a list?
A:
max(strings, key=lambda x: x)
B:
max(strings, key=lambda x: len(x))
C:
max(strings, lambda x: len(x))
D:
max(strings, lambda x: x)
Answer: B
The key parameter is used to specify the lambda function that calculates the length of each string.
Ad Slot (Above Pagination)
Quiz