Sorting and Key Functions
Sort lists, dicts, and objects with sorted() and the key parameter — from simple to multi-criteria sorting.
"Python's sorted() can sort almost anything — as long as you tell it what to compare. The key parameter is that instruction."
— ShurAIsorted() vs .sort()
Python has two ways to sort. Know the difference:
Original is unchanged
Works on any iterable
sorted([3,1,2]) → [1,2,3]
Returns
NoneOnly works on lists
[3,1,2].sort() → list modified
nums = [3, 1, 4, 1, 5, 9, 2]
# sorted() — original untouched
asc = sorted(nums) # [1, 1, 2, 3, 4, 5, 9]
desc = sorted(nums, reverse=True) # [9, 5, 4, 3, 2, 1, 1]
print(nums) # [3, 1, 4, 1, 5, 9, 2] — unchanged!
# .sort() — modifies in place
nums.sort()
print(nums) # [1, 1, 2, 3, 4, 5, 9] — changed!
The key Parameter
Pass a function to key= to control what Python compares when sorting. The function is called on each item to get the sort value:
words = ["banana", "fig", "apple", "elderberry", "date"]
# Sort by length (shortest first)
print(sorted(words, key=len))
# ['fig', 'date', 'apple', 'banana', 'elderberry']
# Sort alphabetically, ignoring case
print(sorted(["Banana", "apple", "Cherry"], key=str.lower))
# ['apple', 'Banana', 'Cherry']
Sorting Objects with lambda
Use a lambda to sort by a specific attribute or dict key:
students = [
{"name": "Riya", "score": 92, "age": 22},
{"name": "Arjun", "score": 75, "age": 25},
{"name": "Sneha", "score": 88, "age": 21},
{"name": "Vikram", "score": 75, "age": 23},
]
# Sort by score, highest first
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
for s in by_score:
print(f"{s['name']}: {s['score']}")
# Riya: 92
# Sneha: 88
# Arjun: 75
# Vikram: 75
Multi-Key Sorting
Return a tuple from the key function to sort by multiple criteria at once:
# Sort by score DESC, then by name ASC for ties
by_score_name = sorted(
students,
key=lambda s: (-s["score"], s["name"]) # negate score for DESC
)
for s in by_score_name:
print(f"{s['score']:3} {s['name']}")
# 92 Riya
# 88 Sneha
# 75 Arjun ← tie at 75: Arjun before Vikram (alphabetical)
# 75 Vikram
Sorting Objects with attrgetter
from operator import attrgetter
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"{self.name}(₹{self.price})"
products = [Product("Rice", 80), Product("Oil", 150), Product("Salt", 25)]
# attrgetter is faster than lambda for attribute access
print(sorted(products, key=attrgetter("price")))
# [Salt(₹25), Rice(₹80), Oil(₹150)]
"Python's sort is stable — items with equal keys keep their original order. This makes multi-key sorting by sorting twice work perfectly: sort by secondary key first, then primary key."
— ShurAI🧠 Quiz — Q1
What is the key difference between sorted() and list.sort()?
🧠 Quiz — Q2
You want to sort a list of strings by their length. Which call is correct?
🧠 Quiz — Q3
How do you sort a list of dicts by the value of key "score", highest first?
🧠 Quiz — Q4
You sort students by key=lambda s: (-s["score"], s["name"]). What does the tuple achieve?