Sub topic 8
Sorting and reversing
This chapter assumes you can create lists, index and slice them, and know that list methods such as append change a list in place. It covers sort, sorted, reverse and reversed, and the key and reverse arguments.
Two ways to sort
Python gives you two tools that look alike but behave differently.
list.sort()reorders the list in place and returnsNone.sorted(iterable)builds and returns a new list. It accepts any iterable, and the original is untouched.
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) # NoneThe last two lines show the most common sorting bug. Writing words = words.sort() replaces your list with None. Use sort() when you want to change the list, and sorted() when you need the original or you are sorting something that is not a list, such as a tuple or the keys of a dictionary.
In the example above, words.sort(reverse=True) happens to leave the list in the same order, because descending alphabetical order is pear, fig, banana.
The key argument
By default, items are compared with <. The key argument is a function that Python calls once for each item. The results of those calls are compared instead of the items themselves. The items stay in the list unchanged.
people = [("Ana", 31), ("Bo", 25), ("Cy", 31)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age) # [('Bo', 25), ('Ana', 31), ('Cy', 31)]
names = ["bob", "Alice", "carol"]
print(sorted(names)) # ['Alice', 'bob', 'carol']
print(sorted(names, key=str.lower)) # ['Alice', 'bob', 'carol']
print(sorted(["b", "A", "c"])) # ['A', 'b', 'c']
print(sorted(["b", "A", "c"], key=str.lower)) # ['A', 'b', 'c']Plain string sorting compares character codes, so every uppercase letter sorts before every lowercase letter. Passing key=str.lower gives a case-insensitive order.
Stability
Sorting in Python is stable. Items with equal keys keep their original relative order. In the example above, Ana stays ahead of Cy because both are 31 and Ana came first. You can use this to sort by several criteria. Sort by the least important criterion first, then by the most important.
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Al", 25)]
people.sort(key=lambda p: p[0]) # by name
people.sort(key=lambda p: p[1]) # then by age
print(people) # [('Al', 25), ('Bo', 25), ('Ana', 31), ('Cy', 31)]Descending order and reversing
reverse=True sorts from largest to smallest. It keeps stability, so equal items still keep their original order. This differs from sorting ascending and then reversing the result.
Reversing is a separate operation that does not compare anything.
list.reverse()flips the list in place and returnsNone.reversed(seq)returns an iterator over the items from the end. Wrap it inlist()if you need a list.- The slice
seq[::-1]returns a new reversed list.
nums = [3, 1, 2]
print(list(reversed(nums))) # [2, 1, 3]
print(nums[::-1]) # [2, 1, 3]
nums.reverse()
print(nums) # [2, 1, 3]Exercise
A learner writes scores = [70, 95, 82] and then scores = scores.sort(reverse=True). What does scores hold afterward, and how should the line be written to get the scores in descending order?
Show answer
scores holds None, because sort changes the list in place and returns None. Write scores.sort(reverse=True) on its own line to get [95, 82, 70], or write scores = sorted(scores, reverse=True).
Exercise
Given names = ["bob", "Alice", "carol"], write one expression that returns the names ordered by length, shortest first, without changing names.
Show answer
sorted(names, key=len) returns ['bob', 'carol', 'Alice']. Both carol and Alice have length 5, so stability keeps carol ahead of Alice, as in the original list.