Example 1 — Rank Exam Scores and Show the Top Three
Sort in place, see that the return value is None, then sort high to low and slice the top three.
scores = [88, 92, 75, 92, 60]
ranked = scores.sort()
print(ranked)
print(scores)
scores.sort(reverse=True)
print("top 3:", scores[:3])
print(sorted([5, 3, 9]), sorted("bca")) How It Works
- The classic trap.
ranked = scores.sort()sorts the list but storesNoneinranked. - Sorted in place.
scoresitself is now ascending, with the two 92s side by side. - reverse=True. Sorting again with
reverse=Trueputs the highest scores first, and the slice[:3]takes the top three. - sorted() returns a list. The built-in returns a new sorted list, and on a string it gives a list of characters.

