Programming Search⌘K

Featurecore

Sorting

Also called sort, sorted, list.sort, key function, reverse sort, stable sort, itemgetter, attrgetter, cmp_to_key, sort by multiple keys, Timsort.

list.sort() sorts a list in place and returns None, and sorted() returns a new sorted list from any iterable. Both take a key function and a reverse flag, and both sorts are stable.

Language
Python

Synopsis

print(sorted([5, 2, 3, 1, 4]))
a = [5, 2, 3, 1, 4]
a.sort(reverse=True)
print(a)
print(sorted("This is a test string from Andrew".split(), key=str.casefold))
print(sorted({1: "D", 2: "B", 3: "B"}))
Output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
[1, 2, 3]

sorted() accepts any iterable. A dict gives its keys.

Semantics

r1. "Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable."1 list.sort() "modifies the list in-place (and returns None to avoid confusion)."1 Example: sort-result.

r2. "The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record."1

r3. "Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved."1 "The built-in sorted() function is guaranteed to be stable."2 This lets a program sort in several passes, the secondary key first. Example: multi-pass.

r4. "Both list.sort() and sorted() accept a reverse parameter with a boolean value."1 "The reverse parameter still maintains sort stability (so that records with equal keys retain the original order)."1

r5. "The sort routines use < when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an lt() method".1 Example: lt.

r6. "Python provides functools.cmp_to_key to wrap the comparison function to make it usable as a key function".1 Example: cmp.

r7. "most cross-type comparisons raise a TypeError."1 Also, "None is not comparable to other types."1 Example: mixed.

Examples

from operator import itemgetter, attrgetter

students = [("john", "A", 15), ("jane", "B", 12), ("dave", "B", 10)]
print(sorted(students, key=lambda s: s[2]))
print(sorted(students, key=itemgetter(1, 2)))
print(sorted(students, key=itemgetter(2), reverse=True))
Output
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

itemgetter(1, 2) sorts by grade and then by age.

from operator import itemgetter

data = [("red", 1), ("blue", 1), ("red", 2), ("blue", 2)]
print(sorted(data, key=itemgetter(0)))

students = [("john", "A", 15), ("jane", "B", 12), ("dave", "B", 10)]
s = sorted(students, key=itemgetter(2))
print(sorted(s, key=itemgetter(1), reverse=True))
Output
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The second sort keeps the age order inside each grade (rule r3). The result is grade descending and age ascending.

class Student:
    def __init__(self, name, age):
        self.name, self.age = name, age

    def __lt__(self, other):
        return self.age < other.age

people = [Student("john", 15), Student("dave", 10), Student("jane", 12)]
print([p.name for p in sorted(people)])
print(min(people).name)
Output
['dave', 'jane', 'john']
dave
from functools import cmp_to_key

def by_length_then_text(a, b):
    if len(a) != len(b):
        return len(a) - len(b)
    return (a > b) - (a < b)

print(sorted(["bb", "a", "ccc", "ab"], key=cmp_to_key(by_length_then_text)))
print(sorted(["bb", "a", "ccc", "ab"], key=lambda w: (len(w), w)))
Output
['a', 'ab', 'bb', 'ccc']
['a', 'ab', 'bb', 'ccc']

A tuple key often does the same job as a comparison function (rule r6).

Pitfalls

list.sort() returns None:

This code runs but gives a wrong answer on purpose.

names = ["b", "a"]
ordered = names.sort()
print(ordered, names)
Output
None ['a', 'b']

Use sorted(names) when the program needs a new list (rule r1).

Values that cannot be compared cannot be sorted:

This code raises TypeError, on purpose.

sorted([3.3, None, 1.1])

Remove the None values first, for example sorted(x for x in data if x is not None) (rule r7).

Comparison

Go sorts with a comparison function, and its basic sort is not stable. The Go documentation says: "SortFunc sorts the slice x in ascending order as determined by the cmp function. This sort is not guaranteed to be stable."3 A Go program calls SortStableFunc to keep equal items in order. Every Python sort is stable (rule r3), and the usual tool is a key function, not a comparison function.

References

  1. Sorting Techniques, Python 3.15 documentation, Sorting Basics; Key Functions; Sort Stability; Comparison Functions; Strategies For Unorderable Types
  2. Built-in Functions, Python 3.15 documentation, sorted()
  3. slices package, Go standard library, SortFunc; SortStableFunc

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source