Sub topic 8
Sorting and reversing
This chapter assumes you can create lists, index them, and call methods. It also assumes you know that some list methods change the list in place and return None. If that last point is unfamiliar, review the chapter on mutability first.
Two ways to sort
Python gives you two tools for sorting, and they differ in one way: whether they change the original list.
list.sort()reorders the list in place and returnsNone.sorted(iterable)builds and returns a new list and leaves the original alone.
words = ["pear", "fig", "banana"]
print(sorted(words, key=len)) # ['fig', 'pear', 'banana']
print(words) # ['pear', 'fig', 'banana'] (unchanged)
result = words.sort(reverse=True)
print(words) # ['pear', 'fig', 'banana']
print(result) # NoneIn this example words.sort(reverse=True) happens to give the same order the list started with. Reverse alphabetical order is pear, fig, banana, which matches the original. The important line is the last one: result is None.
A common bug is writing words = words.sort(). This replaces your list with None. Use words.sort() as a statement on its own line, or use sorted() when you want a value back.
sorted() accepts any iterable, not only lists. It always returns a list:
print(sorted("hello")) # ['e', 'h', 'l', 'l', 'o']
print(sorted({"b": 1, "a": 2})) # ['a', 'b']
print(sorted((3, 1, 2))) # [1, 2, 3]list.sort() exists only on lists. Choose it when you own the list and do not need the old order. It avoids allocating a second list. Choose sorted() when the input is not a list, when other code still holds the original order, or when you want to sort inside an expression.
The key argument
By default, Python compares the items themselves with <. The key argument lets you sort by something computed from each item. You pass a function that takes one item and returns the value to compare.
names = ["bob", "Alice", "carol", "Dave"]
print(sorted(names)) # ['Alice', 'Dave', 'bob', 'carol']
print(sorted(names, key=str.lower)) # ['Alice', 'bob', 'carol', 'Dave']The default sort puts every uppercase letter before every lowercase letter, because it compares character codes. Using key=str.lower compares the lowercase versions but returns the original items.
Three details matter here:
- The key function runs exactly once per item. Python stores the computed keys and compares those, so an expensive key function is not repeated at each comparison.
keyandreverseare keyword-only.sorted(names, str.lower)raises aTypeError.- The key function can be any callable: a built-in such as
len, a method such asstr.lower, alambda, or a function you define.
For records, operator.itemgetter and operator.attrgetter are clear alternatives to a lambda:
from operator import itemgetter
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25)]
print(sorted(people, key=itemgetter(1)))
# [('Bo', 25), ('Di', 25), ('Ana', 31), ('Cy', 31)]Descending order with reverse
Pass reverse=True to sort from largest to smallest:
scores = [70, 95, 82, 95, 60]
print(sorted(scores, reverse=True)) # [95, 95, 82, 70, 60]You could sort ascending and then flip the list, but reverse=True is better for one reason: it keeps the sort stable, as the next section explains.
Stability
Python's sort is stable. Items that compare equal keep the order they had in the input. This holds for sort() and sorted(), and it also holds when reverse=True is used.
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age)
# [('Bo', 25), ('Di', 25), ('Ana', 31), ('Cy', 31)]
by_age_desc = sorted(people, key=lambda p: p[1], reverse=True)
print(by_age_desc)
# [('Ana', 31), ('Cy', 31), ('Bo', 25), ('Di', 25)]In both results, Bo stays ahead of Di and Ana stays ahead of Cy, because that was their order in the input. If you had sorted ascending and then called .reverse(), the ties would come out flipped: Di before Bo, and Cy before Ana. Whether that matters depends on your data, but it is the reason to prefer reverse=True.
Sorting on more than one field
Stability gives you two ways to sort by several fields.
Tuple keys. Return a tuple from the key function. Python compares tuples element by element. To sort one field descending, negate it if it is a number:
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25)]
print(sorted(people, key=lambda p: (-p[1], p[0])))
# [('Ana', 31), ('Cy', 31), ('Bo', 25), ('Di', 25)]This sorts by age descending, then by name ascending.
Repeated sorts. Sort by the least important field first, then by the next field, and so on. Stability preserves the earlier order among ties. This works for fields that cannot be negated, such as strings:
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25)]
people.sort(key=lambda p: p[0], reverse=True) # name, descending
people.sort(key=lambda p: p[1]) # age, ascending
print(people)
# [('Di', 25), ('Bo', 25), ('Cy', 31), ('Ana', 31)]The final sort is by age. Within each age, the names remain in descending order from the first pass.
Reversing without sorting
Reversing flips the current order and does not compare anything. There are three tools, and they differ in what they return:
| Tool | Changes original | Returns | Notes |
|---|---|---|---|
| `lst.reverse()` | Yes | `None` | In place, only for lists |
| `reversed(lst)` | No | Iterator | Lazy; wrap in `list()` to get a list |
| `lst[::-1]` | No | New list | Slice with step -1 |
nums = [1, 2, 3]
print(list(reversed(nums))) # [3, 2, 1]
print(nums[::-1]) # [3, 2, 1]
print(nums) # [1, 2, 3]
nums.reverse()
print(nums) # [3, 2, 1]Printing reversed(nums) directly shows something like <list_reverseiterator object ...>, not the items. Loop over it or convert it with list(). Like any iterator, it can be consumed only once.
For a loop that only reads the items backwards, for x in reversed(nums): avoids copying the list and is the clearest form.
Errors and gotchas
Mixed types cannot be compared
Python 3 refuses to order values that have no defined ordering between them:
mixed = [3, "a", 1]
try:
sorted(mixed)
except TypeError as err:
print(err) # '<' not supported between instances of 'str' and 'int'Fix this by converting the items to one type, filtering out the odd ones, or supplying a key that maps every item to a comparable value. For example, sorted(mixed, key=str) sorts everything as text.
None values
None cannot be compared to numbers either. If your data contains missing values, build a key that puts them somewhere definite:
data = [5, None, 2, None, 9]
print(sorted(data, key=lambda x: (x is None, x if x is not None else 0)))
# [2, 5, 9, None, None]The key is a tuple. The first element is False for real numbers and True for None, so None values go last. The second element is only used to order the real numbers.
NaN breaks ordering
float("nan") compares false against everything, including itself. A list containing NaN does not sort predictably, and the result depends on where the NaN started. Remove NaN values before sorting, or map them to a fixed key.
Do not modify a list while it sorts
During list.sort(), CPython makes the list appear empty. If your key function tries to change the list, Python raises ValueError: list modified during sort. Keep key functions free of side effects.
Sorting is by position of equal items, not identity
Sorting does not remove duplicates. sorted([95, 95, 82]) keeps both 95s. To remove duplicates first, use sorted(set(values)), which gives a sorted list of unique values (the items must be hashable).
Cost
Both sort() and sorted() use Timsort. It takes O(n log n) time in general and is close to O(n) when the data is already mostly ordered. sorted() needs O(n) extra memory for the new list. list.sort() needs temporary working space too, but it does not create a second full list for the caller.
If you only need the largest or smallest few items, heapq.nlargest(k, data) and heapq.nsmallest(k, data) can be cheaper than sorting everything. For finding just the single largest or smallest, max() and min() are better.
Summary of decisions
- Use
sort()to reorder a list you own. Usesorted()to get a new list or to sort a non-list. - Use
keyto sort by a computed value, andreverse=Truefor descending order. - Rely on stability for multi-field sorts, or return a tuple from the key.
- Never assign the result of
sort()orreverse()to a variable.
Exercise
You have orders = [("b", 3), ("a", 3), ("c", 1)]. Write one expression that returns a new list sorted by the number in descending order, with ties sorted by the letter in ascending order. Why does orders = orders.sort(key=lambda o: o[1]) leave you with a broken variable?
Show answer
Use sorted(orders, key=lambda o: (-o[1], o[0])), which gives [('a', 3), ('b', 3), ('c', 1)]. The number is negated so that larger numbers come first, and the letter breaks ties in ascending order. The assignment fails because list.sort() sorts in place and returns None, so orders becomes None and the data is lost.
Exercise
A list holds ["Banana", "apple", "cherry"]. What does sorted() return with no arguments, and how do you get ['apple', 'Banana', 'cherry']?
Show answer
The default sort compares character codes, and uppercase letters come before lowercase ones, so the result is ['Banana', 'apple', 'cherry']. Use sorted(items, key=str.lower) to compare the lowercase versions while keeping the original strings.
Exercise
You need to loop over a very large list from last item to first, without changing it and without making a copy. Which tool do you use, and what happens if you try to loop over the result twice?
Show answer
Use reversed(lst), which returns a lazy iterator and makes no copy. An iterator can be consumed only once, so the second loop sees no items. Call reversed(lst) again for each loop.