This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Sorting and Key Functions, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
Which call returns a new sorted list?
Answer: sorted(items)
Why: sorted returns a new list; sort changes the list in place.
What does the key argument do?
Answer: Selects the value used for comparison
Why: key receives an item and returns the value Python should compare.
What does enumerate provide?
Answer: Indexes and values
Why: Each iteration yields an index and the matching value.
What does list(zip([1, 2], ["a", "b"])) produce?
Answer: [(1, 'a'), (2, 'b')]
Why: zip pairs items at the same position from each sequence.
Complete the argument that sorts from largest to smallest.
prices = [3.0, 6.0, 4.5]
print(sorted(prices, ____=True))Answer: reverse
Why: reverse=True reverses the comparison order.
Complete the small anonymous function used as a key.
orders = [("latte", 4.5), ("tea", 3.0)]
print(sorted(orders, key=____ item: item[1]))Answer: lambda
Why: lambda item: item[1] returns the second field for sorting.
Complete the function that adds indexes to the loop.
names = ["latte", "tea"]
for i, name in ____(names):
print(i, name)Answer: enumerate
Why: enumerate(names) yields an index and a name on each iteration.
Complete the function that pairs the two sequences.
names = ["latte", "tea"]
prices = [4.5, 3.0]
for name, price in ____(names, prices):
print(name, price)Answer: zip
Why: zip(names, prices) pairs each name with the price at the same position.
What is the output?
print(sorted([3, 1, 2]))Answer: [1, 2, 3]
Why: sorted returns the values in ascending order.
What does this code print?
print(sorted(["bb", "a", "ccc"], key=len))Answer: ['a', 'bb', 'ccc']
Why: The strings are ordered by length.
What does the program output?
print(list(enumerate(["a", "b"])))Answer: [(0, 'a'), (1, 'b')]
Why: enumerate pairs each value with its index.
What appears on the screen?
print(max([4, 9, 2]))Answer: 9
Why: max returns the largest value.
Try the questions first
Open the practice page for Python Sorting and Key Functions and answer the same 12 questions with instant feedback.