9. Use heapq for top-N selection
If you only need a few smallest or largest items, avoid sorting the entire collection.
Partial selection algorithms matter when the collection is large and you only care about a small slice of it. heapq expresses that intent directly and avoids paying the readability and runtime cost of a full sort when you do not need one.
9.1. Don’t do this
1top_scores = sorted(scores, reverse=True)[:3]
9.2. Do this
1from heapq import nlargest
2
3top_scores = nlargest(3, scores)