Focused practice · 7 min read

Python Sorting Exercises: key, reverse, and Record Order

Sorting a list of numbers is only the first step. The useful skill is sorting records by a chosen field while keeping the original data intact.

sorted or sort?

sorted returns a new list. sort changes the existing list and returns None. Choose based on whether the original order still has value. A quick print before and after makes the difference visible.

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

A new list, then the original

Sort records by a field

Pass a key function that returns the field to compare. A lambda is enough for a short rule. The records themselves do not change; Python only uses the returned key while sorting.

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

Sort by price

Reverse and extremes

reverse=True flips the order. min and max return an item, not a sorted list. When records are involved, use a key with min or max to choose the field that defines the extreme.

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

Descending and maximum

Pair data with zip and enumerate

zip pairs values at the same position. enumerate adds an index. Combining them is useful when a report needs a row number and two related fields. Stop conditions follow the shorter sequence.

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

Numbered pairs

Keep a stable tie-breaker

A key can return a tuple when you need more than one field. Python compares the first element, then the next. Use that to sort by price and then by name without writing a custom comparison.

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

Price, then name

Your practice checklist

Common questions

Why did my list become None?

You probably assigned the result of sort() back to the list. Call items.sort() on its own, or use items = sorted(items).

How do I sort by the second item in a tuple?

Use key=lambda item: item[1]. The lambda returns the field Python should compare.

Does zip stop at the longer list?

No. zip stops when the shortest input is exhausted, so missing values are silently left out.

Practice sorting

12 questions on sorted, sort, key functions, reverse, zip, and enumerate.

Open practice

Keep reading: