Hackerrank Built-in Functions and Lambdas 2 — Questions and Answers
Question 1: What does `list(map(lambda x: x ** 2, [1, 2, 3, 4]))` return?
- [1, 4, 9, 16] (Correct answer)
- [2, 4, 6, 8]
- [1, 2, 3, 4]
- [1, 8, 27, 64]
Correct answer: [1, 4, 9, 16]
map applies the lambda squaring function to each element, producing [1, 4, 9, 16].
Question 2: Which built-in function returns the largest item in an iterable?
- max() (Correct answer)
- top()
- largest()
- peak()
Correct answer: max()
max() returns the largest item from an iterable or the largest of two or more arguments.
Question 3: What is the output of `list(filter(lambda x: x % 2 == 0, range(10)))`?
- [0, 2, 4, 6, 8] (Correct answer)
- [1, 3, 5, 7, 9]
- [2, 4, 6, 8, 10]
- [0, 1, 2, 3, 4]
Correct answer: [0, 2, 4, 6, 8]
filter keeps elements where the lambda returns True, selecting even numbers 0 through 8.
Question 4: What does `abs(-7.5)` return?
- 7.5 (Correct answer)
- -7.5
- 7
- 8
Correct answer: 7.5
abs() returns the absolute value of a number, converting -7.5 to 7.5.
Question 5: What is the result of `sorted([3,1,4,1,5], reverse=True)`?
- [5, 4, 3, 1, 1] (Correct answer)
- [1, 1, 3, 4, 5]
- [5, 4, 3, 2, 1]
- [3, 1, 4, 1, 5]
Correct answer: [5, 4, 3, 1, 1]
sorted() with reverse=True returns a new list sorted in descending order.
Question 6: Which of the following correctly uses a lambda with `sorted()` to sort by the second element of each tuple?
- sorted(lst, key=lambda x: x[1]) (Correct answer)
- sorted(lst, key=lambda x: x[0])
- sorted(lst, lambda x: x[1])
- sorted(lst, func=lambda x: x[1])
Correct answer: sorted(lst, key=lambda x: x[1])
The key parameter accepts a callable; lambda x: x[1] extracts the second element for comparison.
Question 7: What does `any([False, False, True, False])` return?
- True (Correct answer)
- False
- None
- 1
Correct answer: True
any() returns True if at least one element in the iterable is truthy.
What does `list(map(lambda x: x ** 2, [1, 2, 3, 4]))` return?