Skip to main content
Editor

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

Intermediate25 min7 exercises115 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/7 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
# sort() modifies the original list
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers) # [1, 2, 5, 8, 9] - the list itself changed
Output
[1, 2, 5, 8, 9]
sorted() creates a new list
# sorted() returns a NEW sorted list
numbers = [5, 2, 8, 1, 9]
result = sorted(numbers)
print(result) # [1, 2, 5, 8, 9] - a new list
print(numbers) # [5, 2, 8, 1, 9] - original unchanged!
Output
[1, 2, 5, 8, 9]
[5, 2, 8, 1, 9]
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
# sorted() works on strings too
letters = sorted("python")
print(letters) # ['h', 'n', 'o', 'p', 't', 'y']
# sorted() works on tuples
coords = sorted((3, 1, 4, 1, 5))
print(coords) # [1, 1, 3, 4, 5] - result is always a list
Output
['h', 'n', 'o', 'p', 't', 'y']
[1, 1, 3, 4, 5]

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
scores = [72, 95, 88, 61, 100]
# Ascending (default)
print(sorted(scores)) # [61, 72, 88, 95, 100]
# Descending
print(sorted(scores, reverse=True)) # [100, 95, 88, 72, 61]
Output
[61, 72, 88, 95, 100]
[100, 95, 88, 72, 61]

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

Reverse sorting strings
fruits = ['banana', 'apple', 'cherry', 'date']
print(sorted(fruits)) # ['apple', 'banana', 'cherry', 'date']
print(sorted(fruits, reverse=True)) # ['date', 'cherry', 'banana', 'apple']
Output
['apple', 'banana', 'cherry', 'date']
['date', 'cherry', 'banana', 'apple']

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
# Sort words by length instead of alphabetically
words = ['banana', 'pie', 'strawberry', 'kiwi']
result = sorted(words, key=len)
print(result) # ['pie', 'kiwi', 'banana', 'strawberry']
Output
['pie', 'kiwi', 'banana', 'strawberry']

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
# Without key - uppercase letters sort before lowercase
names = ['alice', 'Bob', 'CHARLIE', 'dave']
print(sorted(names)) # ['Bob', 'CHARLIE', 'alice', 'dave']
# With key=str.lower - true alphabetical order
print(sorted(names, key=str.lower)) # ['alice', 'Bob', 'CHARLIE', 'dave']
Output
['Bob', 'CHARLIE', 'alice', 'dave']
['alice', 'Bob', 'CHARLIE', 'dave']

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
# Sort numbers by their last digit
numbers = [23, 45, 12, 67, 34, 89]
result = sorted(numbers, key=lambda x: x % 10)
print(result) # [12, 23, 34, 45, 67, 89]
Output
[12, 23, 34, 45, 67, 89]

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
# Sort strings by their last character
words = ['hello', 'zebra', 'apple', 'mango']
result = sorted(words, key=lambda w: w[-1])
print(result) # ['zebra', 'apple', 'mango', 'hello']
Output
['zebra', 'apple', 'hello', 'mango']
Multi-criteria sorting with tuples
# Sort by length first, then alphabetically
words = ['cat', 'bat', 'elephant', 'ant', 'dog']
result = sorted(words, key=lambda w: (len(w), w))
print(result) # ['ant', 'bat', 'cat', 'dog', 'elephant']
Output
['ant', 'bat', 'cat', 'dog', 'elephant']

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
students = [
{'name': 'Alice', 'grade': 92},
{'name': 'Bob', 'grade': 85},
{'name': 'Charlie', 'grade': 97},
{'name': 'Diana', 'grade': 88},
]
# Sort by grade (ascending)
by_grade = sorted(students, key=lambda s: s['grade'])
for s in by_grade:
print(f"{s['name']}: {s['grade']}")
Output
Bob: 85
Diana: 88
Alice: 92
Charlie: 97
Sorting dictionaries in descending order
students = [
{'name': 'Alice', 'grade': 92},
{'name': 'Bob', 'grade': 85},
{'name': 'Charlie', 'grade': 97},
{'name': 'Diana', 'grade': 88},
]
# Sort by grade (highest first)
top_students = sorted(students, key=lambda s: s['grade'], reverse=True)
for s in top_students:
print(f"{s['name']}: {s['grade']}")
Output
Charlie: 97
Alice: 92
Diana: 88
Bob: 85

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
prices = {'banana': 0.25, 'apple': 0.75, 'cherry': 3.25, 'date': 1.75}
# Sort by key (fruit name)
for fruit in sorted(prices):
print(f"{fruit}: ${prices[fruit]}")
print()
# Sort by value (price)
for fruit in sorted(prices, key=lambda f: prices[f]):
print(f"{fruit}: ${prices[fruit]}")
Output
apple: $0.75
banana: $0.25
cherry: $3.25
date: $1.75

banana: $0.25
apple: $0.75
date: $1.75
cherry: $3.25

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
students = [
{'name': 'Alice', 'grade': 90},
{'name': 'Bob', 'grade': 85},
{'name': 'Charlie', 'grade': 90},
{'name': 'Diana', 'grade': 85},
]
# Sort by grade - ties keep original order
result = sorted(students, key=lambda s: s['grade'])
for s in result:
print(f"{s['name']}: {s['grade']}")
# Bob: 85, Diana: 85, Alice: 90, Charlie: 90
# Bob comes before Diana (original order preserved)
# Alice comes before Charlie (original order preserved)
Output
Bob: 85
Diana: 85
Alice: 90
Charlie: 90

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.

scores = [78, 92, 65, 88, 95, 71]
# Print scores low to high
# Print scores high to low
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.

nums = [3, 1, 4, 1, 5]
result = nums.sort()
print(result)
print(nums)
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.

words = ['elephant', 'cat', 'giraffe', 'ox', 'bear', 'ant']
# Sort by length and print
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']

names = ['Charlie', 'alice', 'Eve', 'dave', 'Bob']
result = sorted(names)
print(result)
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

students = [
{'name': 'Alice', 'grade': 88},
{'name': 'Bob', 'grade': 95},
{'name': 'Charlie', 'grade': 72},
{'name': 'Diana', 'grade': 91},
]
# Sort by grade (highest first) and print each student
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

products = [
{'name': 'Banana', 'category': 'fruit', 'price': 1.20},
{'name': 'Milk', 'category': 'dairy', 'price': 3.50},
{'name': 'Apple', 'category': 'fruit', 'price': 0.80},
{'name': 'Cheese', 'category': 'dairy', 'price': 5.00},
{'name': 'Cherry', 'category': 'fruit', 'price': 4.00},
{'name': 'Yogurt', 'category': 'dairy', 'price': 2.50},
]
# Sort by category, then by price within each category
Ranks with Ties
Stretch

Write a function rank_players(scores) that takes a list of (name, score) tuples and returns a list of (rank, name) tuples for a results table:

  • The highest score comes first. Players with the same score are listed in alphabetical order and share a rank.
  • After a tie, the next rank skips the places the tie used: 1, 2, 2, 4.
  • rank_players([("ann", 90), ("bob", 95), ("cy", 90), ("dee", 80)])
    # [(1, 'bob'), (2, 'ann'), (2, 'cy'), (4, 'dee')]

    Return the answer instead of printing it: Check calls rank_players() with its own scores, some of them hidden.

    def rank_players(scores):
    pass
    Solution unlocks after your first Check

    Harder problems

    More problems on this topic: Sorting and searching

    Related Tutorials

    Was this tutorial helpful?