Lesson 14 · Beginner · 19 min

Python Sorting and Key Functions

Put data in order by the field you actually care about.

sorted and sortkey functionszip and enumerate

Orders should leave the counter in the order they were paid, except the rush orders. Sorting by one field is easy; sorting by two is where tuples start. Which field goes first, and why?

Sorting is easy until records have several fields. Python lets you pass a key function that turns each item into the value used for comparison. That keeps the original records intact and makes the sorting rule explicit. You will also layer stable sorts, mix directions with tuple keys, and use min or max instead of sorting for one record.

sorted returns a new list

sorted(items) creates a new sorted list and leaves the original alone. items.sort() changes the list in place and returns None. Use sorted when you still need the original order.

prices = [6.0, 4.5, 3.25]
print(sorted(prices))
print(prices)

A new sorted list

Sort records with key

key receives one item and returns the value Python should compare. A lambda is a compact function for a short rule. Here the second field, the price, is the sort key.

orders = [("latte", 4.5), ("tea", 3.0), ("mocha", 5.0)]
for name, price in sorted(orders, key=lambda item: item[1]):
    print(name, price)

Sorting tuples by price

enumerate and zip

enumerate gives you an index and a value together. zip pairs items from two sequences. Both keep loops readable when you need position or parallel data.

names = ["latte", "tea"]
prices = [4.5, 3.0]
for i, (name, price) in enumerate(zip(names, prices), 1):
    print(i, name, price)

Index and paired data

Stable sort lets you layer rules

Python's sort is stable: equal keys keep their previous order. Sort by the secondary rule first, then by the primary rule. The second pass preserves the first wherever the primary key ties, so ties remain alphabetical.

orders = [
    {"name": "tea", "price": 3.0},
    {"name": "latte", "price": 4.5},
    {"name": "mocha", "price": 4.5},
]
by_name = sorted(orders, key=lambda order: order["name"])
by_price = sorted(by_name, key=lambda order: order["price"], reverse=True)
for order in by_price:
    print(order["name"], order["price"])

Secondary sort first, primary sort last

Tuple keys mix fields, not directions

A tuple key compares left to right. (-price, name) gives descending price and ascending name because the negative number reverses only that field. reverse=True would reverse both fields, which is rarely the intent.

orders = [("latte", 4.5), ("tea", 3.0), ("mocha", 4.5)]
for name, price in sorted(orders, key=lambda item: (-item[1], item[0])):
    print(name, price)

Reverse one field with a computed key

Find one record without sorting

If you only need the cheapest item, min() with a key is clearer and cheaper than a full sort. max() works the same way. Keep the key function identical to the rule you would use for sorting.

orders = [("latte", 4.5), ("tea", 3.0), ("mocha", 5.0)]
cheapest = min(orders, key=lambda item: item[1])
priciest = max(orders, key=lambda item: item[1])
print(cheapest)
print(priciest)

One extreme does not need a full order

Key points

  • sorted returns a new list; sort changes the list in place.
  • key decides which value is compared.
  • reverse=True sorts from largest to smallest.
  • enumerate adds indexes; zip walks two sequences together.
  • Stable sorts compose; tuple keys can reverse one field without reversing the others.

Common mistakes

  • Assigning the result of sort() back to the list, which stores None.
  • Calling the key function instead of passing it without parentheses.
  • Assuming zip keeps going after the shorter sequence ends.
  • Using reverse=True and expecting the secondary field to stay ascending.
Your turn

Sort three (name, price) tuples by price, then print each name and price.

Try it yourself

Change the values, predict the output, then run the code. The Python runtime is downloaded the first time you press Run, so the first run can take a few seconds.

In-browser PythonRuns locally · no account
First run downloads Pyodide from a CDN. Use Run code after editing.

Practice this lesson

12 questions with immediate explanations.

See all 12 answersStart practice
← comprehensionsclasses →