After this lesson you can put any collection in order, sort records by the field you care about, and combine several sort rules. Sorting appears constantly: leaderboards, price lists, search results, alphabetical names.
sorted and sort
Python has two tools. sorted() is a function that takes any collection and returns a new list, leaving the original unchanged. The list method sort() sorts the list in place and returns None.
marks = [72, 35, 88, 40, 61]
print(sorted(marks))
print(marks)
marks.sort()
print(marks)[35, 40, 61, 72, 88]
[72, 35, 88, 40, 61]
[35, 40, 61, 72, 88]After sorted(marks) the original was still in its old order. After marks.sort() the list itself changed. As the list methods lesson warned, never write marks = marks.sort(), because that stores None.
Because sorted() accepts any collection, it works on tuples, sets, dictionaries (giving the keys) and strings, and always returns a list:
print(sorted((3, 1, 2)))
print(sorted({"pear", "apple", "fig"}))
print(sorted("python"))[1, 2, 3]
['apple', 'fig', 'pear']
['h', 'n', 'o', 'p', 't', 'y']Sorting a set this way is the dependable method of showing one, since the set itself has no guaranteed order.
Reverse order
Add reverse=True for largest first:
print(sorted(marks, reverse=True))
print(sorted(["tea", "coffee", "juice"], reverse=True))[88, 72, 61, 40, 35]
['tea', 'juice', 'coffee']How strings sort
Strings are compared character by character using each character's numeric code. Capital letters come before lowercase ones, and digits before both, which often surprises people:
names = ["chloe", "Ben", "asha", "Daniel"]
print(sorted(names))['Ben', 'Daniel', 'asha', 'chloe']The capitalised names jumped to the front. For a human-friendly alphabetical order, ignore the case by sorting with a key.
The key argument
key is a function. Python calls it on each item and sorts by what it returns, but the items themselves are not changed. To sort case-insensitively, use str.lower:
print(sorted(names, key=str.lower))['asha', 'Ben', 'chloe', 'Daniel']You can sort words by their length with len:
words = ["banana", "fig", "cherry", "kiwi", "apple"]
print(sorted(words, key=len))['fig', 'kiwi', 'apple', 'banana', 'cherry']The shortest words come first. banana and cherry both have six letters, and notice that banana stayed before cherry, as it did in the original list: Python's sort is stable, which means items that tie keep the order they had before. That property is what makes the next trick work.
Sorting records
For a list of dictionaries, the key function picks the field. A tiny function that you write yourself works, and so does a lambda, which is a short unnamed function that you will meet properly in the functions section:
students = [
{"name": "Asha", "marks": 82, "city": "Pune"},
{"name": "Ben", "marks": 75, "city": "Delhi"},
{"name": "Chloe", "marks": 91, "city": "Pune"},
{"name": "Daniel", "marks": 75, "city": "Goa"},
]
by_marks = sorted(students, key=lambda s: s["marks"], reverse=True)
for s in by_marks:
print(s["name"], s["marks"])Chloe 91
Asha 82
Ben 75
Daniel 75For tuples or lists, operator.itemgetter is a ready-made alternative to a lambda, and operator.attrgetter does the same for object attributes:
from operator import itemgetter
pairs = [("pen", 20), ("book", 150), ("ruler", 35)]
print(sorted(pairs, key=itemgetter(1)))[('pen', 20), ('ruler', 35), ('book', 150)]Sorting by more than one field
Return a tuple from the key function. Python compares tuples item by item, so ties on the first field are broken by the second:
ranked = sorted(students, key=lambda s: (-s["marks"], s["name"]))
for s in ranked:
print(s["marks"], s["name"])91 Chloe
82 Asha
75 Ben
75 DanielThe minus sign flips the order for the numbers, so the highest marks come first, while the names within the same marks stay alphabetical. Ben and Daniel both scored 75 and Ben comes first because of his name. Negating only works for numbers. For other types, use stability: sort by the less important field first, then by the more important one:
step1 = sorted(students, key=lambda s: s["name"])
step2 = sorted(step1, key=lambda s: s["city"])
for s in step2:
print(s["city"], s["name"])Delhi Ben
Goa Daniel
Pune Asha
Pune ChloeThe second sort grouped students by city, and thanks to stability the names stayed alphabetical inside each city.
Sorting a dictionary
A dictionary has no sort method, but you can sort its items and build a new dictionary, or just a list of pairs:
sales = {"tea": 40, "coffee": 75, "juice": 25}
print(sorted(sales))
print(sorted(sales.items(), key=lambda pair: pair[1], reverse=True))
print(dict(sorted(sales.items())))['coffee', 'juice', 'tea']
[('coffee', 75), ('tea', 40), ('juice', 25)]
{'coffee': 75, 'juice': 25, 'tea': 40}Since dictionaries keep insertion order, a dictionary built from sorted items stays in that order.
Mixed types cannot be sorted
Python will not guess how to compare a number and a string:
sorted([3, "two", 1])TypeError: '<' not supported between instances of 'str' and 'int'Convert the data to one type first, for example with key=str or by cleaning the values.
Common mistakes
- Assigning the result of
sort(). It returnsNone. Usesorted()if you want the result. - Expecting alphabetical order from capitals and lowercase mixed. Use
key=str.lower. - Calling the key function by hand. Write
key=len, notkey=len(). You pass the function itself. - Sorting mixed types. Numbers and strings cannot be compared. Convert first.
- Forgetting that digits in strings sort as text. The string "10" sorts before "9". Convert with
intto sort by value.
Exercise
Given books = [("Atlas", 320), ("Poems", 90), ("Novel", 320), ("Guide", 150)] as (title, pages), print the list sorted by pages from most to fewest, with titles in alphabetical order when the page counts are equal.
Show one possible answer
books = [("Atlas", 320), ("Poems", 90), ("Novel", 320), ("Guide", 150)]
result = sorted(books, key=lambda b: (-b[1], b[0]))
print(result)[('Atlas', 320), ('Novel', 320), ('Guide', 150), ('Poems', 90)]Previous: Comprehensions. The next section covers functions, where the lambda used above is explained in full.
Key points
- sorted(x) returns a new sorted list and leaves the original alone. list.sort() sorts in place and returns None.
- reverse=True flips the order. The key argument is a function that turns each item into the value to sort by.
- Python's sort is stable: items that compare equal keep their original relative order, which makes multi-step sorts possible.
- Strings sort by character code, so capitals come before lowercase letters. Use key=str.lower for a case-insensitive sort.