Skip to content
CodeItRaw
Sorting

Lesson 1/5

Sorting in Python is one line: sorted(values) gives a new, sorted list; values.sort() sorts the list in place and returns nothing. The real power is in the key parameter: from each element you produce the value it is to be sorted by.

people = [("Ece", 31), ("Can", 25), ("Ada", 31)]
sorted(people, key=lambda p: p[1])
# [("Can", 25), ("Ece", 31), ("Ada", 31)]
sorted(people, key=lambda p: (-p[1], p[0]))
# [("Ada", 31), ("Ece", 31), ("Can", 25)]
The first sort is by age, and those of equal age keep the order they came in (Python's sort is stable). In the second the key is a pair: by age descending first (the minus sign), and by name ascending on a tie.

When the values come in only a few kinds (0, 1 and 2, say) there is no need to sort by comparing: count how many of each there are, then write that many out in order. That is one pass, faster than the general n log n sort.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Sorting by a Key

    Code reading · Predict the Output

  2. 02

    Sort Colors

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list