Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 33 of 70

Sorting in Python: sorted, sort and custom keys

Learn to sort lists, strings and records in Python with sorted() and list.sort(), reverse order, the key argument, multi-level sorts and sorting dictionaries.

14 minCollectionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonSort lists, strings and records with sorted() and sort(), choose the sort rule with key, and sort by several fields at once.

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.

python
marks = [72, 35, 88, 40, 61]
print(sorted(marks))
print(marks)
marks.sort()
print(marks)
result
[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:

python
print(sorted((3, 1, 2)))
print(sorted({"pear", "apple", "fig"}))
print(sorted("python"))
result
[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:

python
print(sorted(marks, reverse=True))
print(sorted(["tea", "coffee", "juice"], reverse=True))
result
[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:

python
names = ["chloe", "Ben", "asha", "Daniel"]
print(sorted(names))
result
['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:

python
print(sorted(names, key=str.lower))
result
['asha', 'Ben', 'chloe', 'Daniel']

You can sort words by their length with len:

python
words = ["banana", "fig", "cherry", "kiwi", "apple"]
print(sorted(words, key=len))
result
['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:

python
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"])
result
Chloe 91
Asha 82
Ben 75
Daniel 75

For tuples or lists, operator.itemgetter is a ready-made alternative to a lambda, and operator.attrgetter does the same for object attributes:

python
from operator import itemgetter

pairs = [("pen", 20), ("book", 150), ("ruler", 35)]
print(sorted(pairs, key=itemgetter(1)))
result
[('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:

python
ranked = sorted(students, key=lambda s: (-s["marks"], s["name"]))
for s in ranked:
    print(s["marks"], s["name"])
result
91 Chloe
82 Asha
75 Ben
75 Daniel

The 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:

python
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"])
result
Delhi Ben
Goa Daniel
Pune Asha
Pune Chloe

The 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:

python
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())))
result
['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:

python
sorted([3, "two", 1])
result
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 returns None. Use sorted() 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, not key=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 int to 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
python
books = [("Atlas", 320), ("Poems", 90), ("Novel", 320), ("Guide", 150)]
result = sorted(books, key=lambda b: (-b[1], b[0]))
print(result)
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.

Check yourself

1. What is the difference between sorted(items) and items.sort()?
2. What does sorted(["pear", "fig", "banana"], key=len) return?
3. How does sorted(["b", "A", "c"]) order its items?
4. What does a stable sort guarantee?