Python Sorting: sort(), sorted(), Key Functions, and Custom Order
Imagine your bookshelf at home. Books are scattered everywhere — some by title, some by color, some shoved in sideways. Finding anything takes forever.
Now imagine organizing that bookshelf alphabetically. Suddenly, finding any book takes seconds. That's the power of sorting — it turns chaos into order.
Python gives you two main tools for sorting: the sort() method and the sorted() function. They look similar but work differently. In this tutorial, you'll learn when to use each one, how to sort in reverse, and how to sort by custom rules using key functions.
What Is the Difference Between sort() and sorted()?
This is the most important distinction in Python sorting. The sort() method changes the original list directly. The sorted() function creates a brand new sorted list and leaves the original untouched.
Think of it this way: sort() is like rearranging the books on your shelf. sorted() is like making a sorted catalog while leaving the shelf exactly as it was.
names = ['Charlie', 'Alice', 'Bob']
result = names.sort()
print(result) # None!names = ['Charlie', 'Alice', 'Bob']
result = sorted(names)
print(result) # ['Alice', 'Bob', 'Charlie']There's another big difference: sorted() works on any iterable — strings, tuples, dictionaries, even generators. The sort() method only works on lists.
How to Sort in Reverse Order
Both sort() and sorted() accept a reverse parameter. Set it to True to sort from highest to lowest instead of lowest to highest.
Strings sort alphabetically by default. With reverse=True, they sort in reverse alphabetical order.
What Are Key Functions in Python Sorting?
Sometimes you don't want to sort by the values themselves. You want to sort by some property of each value. For example, sorting words by their length instead of alphabetically.
The key parameter lets you pass a function that transforms each item before comparison. Python applies this function to every item, then sorts based on the results. The original items stay intact — only the sort order changes.
Here, len is the key function. Python calls len() on each word and uses those lengths to decide the order. "pie" has 3 letters, "kiwi" has 4, and so on.
You can use any function as the key. A common example is case-insensitive sorting using str.lower.
How to Sort with Lambda Functions
Built-in functions like len and str.lower only get you so far. When you need custom sorting logic, you use a lambda — a small, anonymous function written in one line.
A lambda takes an item and returns the value to sort by. The syntax is lambda item: expression.
The lambda lambda x: x % 10 takes each number and returns its last digit (the remainder when divided by 10). Python then sorts by those last digits: 2, 3, 4, 5, 7, 9.
How to Sort Dictionaries and Complex Data
In real programs, you rarely sort plain lists of numbers. More often, you sort lists of dictionaries — like sorting students by grade or products by price.
You can also sort the keys or values of a dictionary itself. The sorted() function iterates over a dictionary's keys by default.
What Is Stable Sorting and Why Does It Matter?
Python uses a sorting algorithm called Timsort, which is stable. This means that when two items are equal according to the sort key, they keep their original order.
This matters a lot in practice. If you sort students by grade and two students have the same grade, they'll stay in whatever order they were in before the sort.
Practice Exercises
You have a list of test scores. Print them sorted from lowest to highest, then on the next line print them sorted from highest to lowest.
Use sorted() so the original list stays unchanged.
Read the code below carefully. What will it print? Remember the key difference between sort() and sorted().
Type the exact output.
Sort the list of words by their length (shortest first). If two words have the same length, they should stay in their original order.
Print the sorted list.
The code below tries to sort names alphabetically, but uppercase and lowercase names are mixing incorrectly. Fix the sort so it works in true alphabetical order regardless of case.
The output should be: ['alice', 'Bob', 'Charlie', 'dave', 'Eve']
Sort the list of students by their grade from highest to lowest. Print each student's name and grade on a separate line in the format: Name: Grade
Sort the list of products first by category (alphabetically), then by price (lowest first) within each category.
Print each product on a separate line in the format: category: name - $price