Skip to main content

Python Sorting: sort(), sorted(), Key Functions, and Custom Order

Intermediate25 min6 exercises85 XP
0/6 exercises

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.

sort() changes the list in place
Loading editor...
sorted() creates a new list
Loading editor...
Bug: Assigning sort() result
names = ['Charlie', 'Alice', 'Bob']
result = names.sort()
print(result)  # None!
Fix: Use sorted() for new list
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.

sorted() works on any iterable
Loading editor...

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.

Sorting in ascending and descending order
Loading editor...

Strings sort alphabetically by default. With reverse=True, they sort in reverse alphabetical order.

Reverse sorting strings
Loading editor...

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.

Sorting by string length with key=len
Loading editor...

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.

Case-insensitive sorting
Loading editor...

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.

Sorting by last digit with a lambda
Loading editor...

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.

Sorting by last character
Loading editor...
Multi-criteria sorting with tuples
Loading editor...

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.

Sorting a list of dictionaries by a key
Loading editor...
Sorting dictionaries in descending order
Loading editor...

You can also sort the keys or values of a dictionary itself. The sorted() function iterates over a dictionary's keys by default.

Sorting dictionary keys and values
Loading editor...

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.

Stable sorting preserves original order for ties
Loading editor...

Practice Exercises

Sort a List of Numbers
Write Code

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.

Loading editor...
Predict the Output: sort() vs sorted()
Predict Output

Read the code below carefully. What will it print? Remember the key difference between sort() and sorted().

Type the exact output.

Loading editor...
Sort Words by Length
Write Code

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.

Loading editor...
Fix the Bug: Case-Sensitive Sorting
Fix the Bug

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']

Loading editor...
Sort Students by Grade
Write Code

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

Loading editor...
Sort by Multiple Criteria
Write Code

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

Loading editor...