Python 3D Academyবাংলা

Python's sort(): Timsort, key=, sorting objects, and choosing a sort

🌍 In real life. At the end of the day the school librarian re-shelves the returned books. The trolley isn't random: a class that borrowed a set of books returns them together, already in order, so the trolley is made of runs that are in order, with a few loose books between them. A smart librarian doesn't start from nothing. She notices the runs, tidies the loose books into short runs, and merges the runs pairwise, the way two piles of scripts were merged in Lesson 45.1.

That is what Python's own sort does. It is called Timsort, after Tim Peters, who wrote it for Python in 2002, and it is behind both sorted() and list.sort().

The idea in one sentence: Timsort finds the runs that are already in order, makes short ones longer with insertion sort, and merges the runs with merge sort's merge, so it is stable, O(n log n) at worst, and close to O(n) on nearly sorted lists.

Its words:

  • run: a stretch of the list already in order (a stretch in reverse order is flipped into one)
  • sorted(x): gives back a new sorted list from anything you can loop over; x.sort() sorts a list in place and gives back None
  • key=: a function that turns each item into the value to compare; it is called once per item
  • reverse=True: biggest first, and still stable: ties keep their order

How Timsort works, step by step:

  1. walk the list finding runs; flip any run that goes down
  2. stretch short runs to a minimum length (32 to 64) with insertion sort (Lesson 44.2), which is quick on short lists
  3. merge the runs pairwise (Lesson 45.1), always taking from the left on a tie, so it stays stable
  4. when merging, "gallop" past long stretches that come from one run, which makes nearly sorted data very fast

Here sorted puts names in order of their length with key=len, biggest first. Rina and Sumi both have 4 letters, and keep their order even with reverse=True:

Sorting objects. Python can only sort things it knows how to compare. Numbers and strings compare naturally; tuples compare item by item. For your own objects, give a key: sorted(players, key=lambda p: p.score), or the shortcut operator.attrgetter("score") (and itemgetter for tuples and dicts). A class can also define __lt__ ("less than"), or use @dataclass(order=True), so its objects compare directly. For a rule that is easiest to say as "which of these two comes first?", functools.cmp_to_key turns a two-item compare function into a key.

Why it is correct, and what it costs. Timsort is made of the two sorts you have already seen, insertion sort and merge, so it sorts for the same reasons, and taking from the left on ties makes it stable. Its cost:

  • already sorted (one run): n − 1 comparisons, O(n)
  • nearly sorted: close to O(n)
  • worst case: O(n log n), like merge sort
  • memory: up to n/2 extra for merging

Choosing a sort.

  • Almost always: sorted() or list.sort(). It is stable, fast, and written in C
  • Small whole-number keys (ages, marks, colours): counting sort, O(n + k)
  • Little extra memory allowed: quick sort with a random pivot, or heap sort (Chapter 49)
  • Linked lists: merge sort, which only walks forwards
  • Only the smallest few: don't sort everything; heapq.nsmallest(k, items) (Chapter 30)
  • Learning, or tiny lists: insertion sort
from dataclasses import dataclass
from functools import cmp_to_key
from operator import attrgetter, itemgetter

class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score

players = [Player("Rina", 40), Player("Ali", 55), Player("Sumi", 40)]
print([p.name for p in sorted(players, key=attrgetter("score"), reverse=True)])

books = [("Rivers of Bangladesh", 2015), ("Stars at Night", 2009), ("Kitchen Science", 2012)]
print(sorted(books, key=itemgetter(1)))

@dataclass(order=True)
class Mark:
    value: int
    name: str

print(sorted([Mark(70, "Bob"), Mark(60, "Dee")]))

# "which of two comes first?": the bigger number when joined in front
by_join = cmp_to_key(lambda a, b: -1 if a + b > b + a else 1)
print("".join(sorted(["3", "30", "34", "5", "9"], key=by_join)))

nums = [5, 3, 8]
print(nums.sort(), nums)               # sort() gives back None

Mistakes and edge cases.

  • nums = nums.sort(): nums becomes None; use nums.sort() alone, or nums = sorted(nums)
  • sorting mixed types: sorted([3, "2", 1]) raises TypeError: '<' not supported between instances of 'str' and 'int'
  • objects with no order: sorting objects without a key or __lt__ raises a TypeError too
  • key=len(): that calls len with nothing; pass the function itself, key=len
  • sorting to find one thing: min() and max() find one value in O(n), and heapq.nsmallest(k, …) the smallest k in O(n log k), cheaper than sorting everything

Quiz

  1. What does this print?

    nums = [3, 1, 2]
    a = sorted(nums)
    b = nums.sort()
    print(a, b, nums)
  2. Python's sort is stable, even with reverse=True. What does this print?

    pairs = [("Rina", 40), ("Ali", 55), ("Sumi", 40), ("Joy", 55)]
    best = sorted(pairs, key=lambda p: p[1], reverse=True)
    print([name for name, score in best])
  3. Why is Python's sort so fast on a list that is already nearly sorted?

    • Timsort finds the long runs already in order and merges them, close to O(n)
    • It is quick sort with a good pivot
    • It skips the list if the first two values are in order
  4. This should print the names from the highest score down, but it raises TypeError. Which line is wrong?

    class Player:
        def __init__(self, name, score):
            self.name = name
            self.score = score
    
    players = [Player("Rina", 40), Player("Ali", 55)]
    ranked = sorted(players, reverse=True)
    print([p.name for p in ranked])
  5. You need the 10 youngest of 50,000 students. What is the best way?

    • heapq.nsmallest(10, students, key=...): no need to sort everything
    • Bubble sort, then take the first 10
    • Sort ten times

Coding tasks

  1. The library catalogue is a list of dicts like {"title": "Stars at Night", "year": 2009}. Write catalogue_order(books): return the titles ordered by year, oldest first, and books from the same year in alphabetical order of title.

  2. Player objects have a name and a score. Write leaderboard(players): return the names from the highest score to the lowest; players with the same score keep the order they joined in (their order in the list).