Reading history

Python Sorting: sorted(), sort() and key Functions

6 min read 1 views

Sort lists, strings and records in Python with sorted() and sort(), reverse, key functions, several keys, itemgetter, attrgetter and stable sorting.

Merit lists, price lists, league tables and search results all need sorting. In Python this takes one line. You can sort numbers, words or whole records, high to low or low to high, and by more than one rule at a time. The secret is the key argument. It tells Python what to compare. This lesson shows how to use it well.

In this lesson you will learn

  • The difference between sorted() and list.sort()
  • Sorting with reverse=True and a key function
  • Sorting records by one field or by several
  • itemgetter and attrgetter from the operator module
  • Why a stable sort matters, and sorting a dictionary by value

You should know lists, dictionaries and lambda functions.

sorted(), sort() and key

# sorted() returns a new list; list.sort() changes the list in place
marks = [72, 95, 58, 88, 64]
print("sorted:        ", sorted(marks))
print("descending:    ", sorted(marks, reverse=True))
print("original kept: ", marks)
marks.sort()
print("after .sort(): ", marks)

# key= tells Python what to compare
cities = ["Sylhet", "dhaka", "Khulna", "Barishal", "Rangpur"]
print(sorted(cities))                    # capital letters come first
print(sorted(cities, key=str.lower))     # ignore case
print(sorted(cities, key=len))           # shortest first

# Sorting records by a field
students = [
    {"name": "Nusrat", "dept": "CSE", "cgpa": 3.82},
    {"name": "Arif",   "dept": "EEE", "cgpa": 3.41},
    {"name": "Tania",  "dept": "CSE", "cgpa": 3.95},
    {"name": "Rafi",   "dept": "EEE", "cgpa": 3.41},
]
best = sorted(students, key=lambda s: s["cgpa"], reverse=True)
print([s["name"] for s in best])

# min, max and the key argument
print("lowest CGPA:", min(students, key=lambda s: s["cgpa"])["name"])
print("longest city name:", max(cities, key=len))

Output

sorted:         [58, 64, 72, 88, 95]
descending:     [95, 88, 72, 64, 58]
original kept:  [72, 95, 58, 88, 64]
after .sort():  [58, 64, 72, 88, 95]
['Barishal', 'Khulna', 'Rangpur', 'Sylhet', 'dhaka']
['Barishal', 'dhaka', 'Khulna', 'Rangpur', 'Sylhet']
['dhaka', 'Sylhet', 'Khulna', 'Rangpur', 'Barishal']
['Tania', 'Nusrat', 'Arif', 'Rafi']
lowest CGPA: Arif
longest city name: Barishal
  • sorted(x) returns a new list and leaves the old one alone. It works on any iterable: a list, a tuple, a string or a dictionary.
  • x.sort() sorts the list in place and returns None. It only works on lists.
  • reverse=True sorts from high to low.
  • Strings sort by character code, so all capital letters come before small ones. That is why “dhaka” came last. key=str.lower compares the lower-case form instead, but the list still holds the original words.
  • The key function is called once for each item. Its result is what gets compared. key=len sorts by length.
  • For records, a lambda picks the field: key=lambda s: s["cgpa"].
  • min and max accept the same key argument.

Several Keys, itemgetter and Stability

from operator import itemgetter, attrgetter
from dataclasses import dataclass

students = [
    ("Nusrat", "CSE", 3.82), ("Arif", "EEE", 3.41), ("Tania", "CSE", 3.95),
    ("Rafi", "EEE", 3.41), ("Mitu", "BBA", 3.67),
]

# Several keys: return a tuple. Department A-Z, then CGPA high to low
by_dept = sorted(students, key=lambda s: (s[1], -s[2]))
for s in by_dept:
    print(f"{s[1]}  {s[2]:.2f}  {s[0]}")

# itemgetter is a faster, named version of lambda s: s[2]
print([s[0] for s in sorted(students, key=itemgetter(2))])

# Stable sort: equal items keep their earlier order.
# Sort by the minor key first, then by the major key.
step1 = sorted(students, key=itemgetter(0))           # by name
step2 = sorted(step1, key=itemgetter(2), reverse=True)  # by CGPA
print([s[0] for s in step2])

# attrgetter for objects
@dataclass
class Book:
    title: str
    year: int
    price: int

books = [Book("Padma Nadir Majhi", 1936, 250), Book("Lalsalu", 1948, 180),
         Book("Hajar Bachhar Dhore", 1964, 220)]
for b in sorted(books, key=attrgetter("year")):
    print(b.year, b.title)

# Sorting a dictionary by its values
sales = {"Pen": 1875, "Book": 2800, "Bag": 2400}
for item, total in sorted(sales.items(), key=itemgetter(1), reverse=True):
    print(f"{item:5} {total}")

Output

BBA  3.67  Mitu
CSE  3.95  Tania
CSE  3.82  Nusrat
EEE  3.41  Arif
EEE  3.41  Rafi
['Arif', 'Rafi', 'Mitu', 'Nusrat', 'Tania']
['Tania', 'Nusrat', 'Mitu', 'Arif', 'Rafi']
1936 Padma Nadir Majhi
1948 Lalsalu
1964 Hajar Bachhar Dhore
Book  2800
Bag   2400
Pen   1875
  • To sort by several rules, return a tuple. Tuples compare item by item, so (dept, -cgpa) sorts by department first. Inside each department, it sorts by CGPA.
  • The minus sign flips one number so it sorts high to low, while the department still sorts A to Z. This trick only works for numbers.
  • itemgetter(2) means the same as lambda s: s[2]. It is a little faster and easy to read. attrgetter("year") does the same for object attributes.
  • Python’s sort is stable: items that compare equal keep their earlier order. Arif and Rafi both have 3.41, and Arif stays first because he was first after the sort by name.
  • Stability lets you sort in two passes: first by the minor rule, then by the main rule. This is handy when one rule is high to low and the other is a string, where the minus trick does not work.
  • sorted(d.items(), key=itemgetter(1)) sorts a dictionary’s pairs by value.

Quick Reference

GoalCode
New sorted listsorted(items)
Sort a list in placeitems.sort()
High to lowsorted(items, reverse=True)
Ignore casesorted(words, key=str.lower)
By a dictionary fieldsorted(rows, key=itemgetter("cgpa"))
By two fieldssorted(rows, key=lambda r: (r["dept"], -r["cgpa"]))
Dictionary by valuesorted(d.items(), key=itemgetter(1))

Common Mistakes

  1. Writing x = x.sort(). sort() returns None, so x becomes None. Use x.sort() on its own line, or x = sorted(x).
  2. Calling the key function. Write key=len, not key=len(). You pass the function itself.
  3. Sorting mixed types. sorted([3, "2", 1]) raises TypeError, because Python will not compare a number with a string.
  4. Using a minus sign on strings. -name is an error. Use two passes or reverse=True instead.

Practice Exercises

Exercise 1. Sort ["banana", "Apple", "cherry", "date"] by length, and alphabetically (ignoring case) when two words have the same length.

Show answer
words = ["banana", "Apple", "cherry", "date"]
print(sorted(words, key=lambda w: (len(w), w.lower())))
# ['date', 'Apple', 'banana', 'cherry']

The tuple compares length first. “banana” and “cherry” both have 6 letters, so the second item breaks the tie.

Exercise 2. Given stock = {"rice": 40, "oil": 12, "sugar": 25}, print the item names from the largest stock to the smallest.

Show answer
stock = {"rice": 40, "oil": 12, "sugar": 25}
print(sorted(stock, key=stock.get, reverse=True))
# ['rice', 'sugar', 'oil']

Looping over a dictionary gives its keys, and stock.get turns each key into its value for comparing.

Frequently Asked Questions

How fast is Python’s sort?

Python uses an algorithm called Timsort. It takes about n log n steps in general and is very fast on data that is already partly sorted. For almost every program, the built-in sort is the best choice.

How do I sort objects of my own class without a key?

Give the class a __lt__ method, which defines “less than”. You can also use @dataclass(order=True), which compares objects field by field in the order they are written.

Summary

  • sorted() returns a new list; list.sort() changes the list and returns None.
  • key decides what is compared; reverse=True sorts high to low.
  • Return a tuple from the key to sort by several rules.
  • The sort is stable, so equal items keep their order.

Next: Python Unpacking and Star Expressions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *