Python Programming - Lambda Functions

Exercise : Lambda Functions - General Questions
  • Lambda Functions - General Questions
51.
What does the following lambda function accomplish?
lambda x: x.capitalize() if isinstance(x, str) else None
Capitalizes the first letter of a string and returns None for non-string values.
Converts a string to uppercase and returns None for non-string values.
Capitalizes the entire 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 capitalizes the first letter of a string and returns None for non-string values.

52.
In Python, how can a lambda function be used with the max() function to find the maximum length string in a list?
max(strings, key=lambda x: x)
max(strings, key=lambda x: len(x))
max(strings, lambda x: len(x))
max(strings, lambda x: x)
Answer: Option
Explanation:
The key parameter is used to specify the lambda function that calculates the length of each string.

53.
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?
sorted(dictionaries, lambda x: x['key'])
sorted(dictionaries, key=lambda x: x['key'])
sorted(dictionaries, sort_key=lambda x: x['key'])
sorted(dictionaries, key='key')
Answer: Option
Explanation:
The key parameter is used to specify the lambda function that extracts the specific key for sorting.

54.
What is the purpose of the functools.lru_cache() function when used with a lambda function?
To create a memoized version of the lambda function.
To create a filter object based on the lambda function's condition.
To sort the elements of an iterable using the lambda function.
To apply the lambda function to each element of an iterable.
Answer: Option
Explanation:
functools.lru_cache() is used to create a memoized version of a function, including lambda functions, for efficient caching of results.

55.
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)
[1, 4, 3, 16, 5]
[1, 4, 9, 16, 25]
[1, 2, 3, 4, 5]
[1, 2, 9, 4, 25]
Answer: Option
Explanation:
The lambda function squares even numbers and leaves odd numbers unchanged.