This sorts the list in ascending order: [1, 2, 3, 4].
Step 2: Apply items.reverse()
This reverses the sorted list, resulting in [4, 3, 2, 1].
Final Answer:
[4, 3, 2, 1] -> Option C
Quick Check:
sort() then reverse() = descending list [OK]
Hint: sort() then reverse() = descending order [OK]
Common Mistakes:
Thinking reverse() sorts the list
Assuming print shows original list
Confusing order of method calls
4. The following code is intended to sort the list data in descending order. What is wrong?
data = [5, 2, 9, 1]
data.reverse()
data.sort()
print(data)
medium
A. The code will cause a syntax error.
B. The reverse() call should come after sort().
C. The sort() method does not exist for lists.
D. The list is already sorted, so no change happens.
Solution
Step 1: Analyze method order
The code reverses the list first, then sorts it ascending, which cancels the reverse effect.
Step 2: Correct method order for descending sort
To get descending order, first sort ascending, then reverse the list.
Final Answer:
The reverse() call should come after sort(). -> Option B
Quick Check:
sort() then reverse() = descending order [OK]
Hint: Sort first, then reverse for descending order [OK]
Common Mistakes:
Reversing before sorting cancels sorting effect
Thinking reverse() sorts the list
Assuming method order does not matter
5. You have a list of words: words = ['apple', 'banana', 'cherry', 'date']. You want to sort them in reverse alphabetical order without changing the original list. Which code snippet achieves this?
hard
A. sorted_words = words.sort(reverse=True)
B. words.sort(reverse=True)
C. words.reverse(); words.sort()
D. sorted_words = sorted(words, reverse=True)
Solution
Step 1: Understand difference between sort() and sorted()
sort() changes the original list; sorted() returns a new sorted list.
Step 2: Choose method that sorts in reverse without changing original
Using sorted(words, reverse=True) returns a new list sorted in reverse alphabetical order, leaving words unchanged.
Final Answer:
sorted_words = sorted(words, reverse=True) -> Option D
Quick Check:
sorted() returns new sorted list [OK]
Hint: Use sorted() to keep original list unchanged [OK]