← Python Intermediate
8 / 25
Lesson 8 — Sorting with key
Custom order
sorted(items) returns a new sorted list, smallest first. Pass key= a function and Python sorts by the value that function returns for each item, not by the item itself. Add reverse=True to flip the order.
nums = [-5, 2, -1]
print(sorted(nums, key=abs)) # [-1, 2, -5]
Why it matters: real data is sorted by something specific — price, date, name length — and key is how you say which.
Want it another way?
Task
Print the words sorted by length, shortest first.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.