Skip to Content
Course content

35: Sorting Lists with sort() and sorted()

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you have a stack of printed invoices sitting on your desk. You realize they're in a random jumble, and you need them in date order. You have two ways to handle this. First, you could physically slide the papers around on your desk until the original stack is organized. Now, the original pile is sorted, but the previous "random" order is gone forever. Or, you could take that stack to the photocopier, make a copy of every page, and organize those copies into a new pile. In the second scenario, you have a sorted list, but your original, messy stack is still sitting exactly where you left it.

In Python, this is exactly the difference between .sort() and sorted(). One changes the original list (the desk), and the other gives you a brand new one (the photocopy).

Changing the Original with .sort()

When you call the .sort() method on a list, you're telling Python to rearrange the items inside that specific list. It's called "in-place" sorting. I usually use this when I don't care about the original order and want to save a bit of memory by not creating a second list.

# Let's say we have a list of usernames
users = ["zara", "alex", "morgan", "ben"]
users.sort()
print(users) 
# Output: ['alex', 'ben', 'morgan', 'zara']

One thing that trips up a lot of people: .sort() returns None. If you try to write my_list = users.sort(), you'll accidentally wipe out your list and replace it with None. Don't do that. Just call the method on its own line.

Creating a Copy with sorted()

If you need to keep the original data exactly as it was—maybe for an audit trail or because another part of your program expects the original sequence—use the sorted() function. This doesn't touch the original list; it just hands you back a new, sorted version of it.

original_scores = [42, 7, 99, 12]
ranked_scores = sorted(original_scores)

print(original_scores) # [42, 7, 99, 12] - Still messy!
print(ranked_scores)   # [7, 12, 42, 99] - All clean.

Flipping the Order and Custom Logic

By default, Python sorts everything in ascending order (A-Z or smallest to largest). If you want the opposite, you don't need to sort and then reverse the list in two steps. Both .sort() and sorted() accept a reverse=True argument.

But the real power comes from the key parameter. This lets you tell Python, "Don't sort based on the item itself; sort based on this specific characteristic of the item." For example, if you want to sort a list of names by the length of the name rather than alphabetically, you pass the len function as the key.

names = ["Christopher", "Amy", "Joe", "Alexandra"]
# Sort by the length of the string
names.sort(key=len)
print(names) 
# Output: ['Amy', 'Joe', 'Alexandra', 'Christopher']

I find the key parameter incredibly useful when dealing with complex data, like lists of dictionaries or tuples, where you only want to sort by one specific field.




📋 Practical Task

The High-Score Leaderboard Organizer

You are building a gaming leaderboard. You have a list of players and their scores stored as tuples: ("PlayerName", score). Your goal is to display the leaderboard from the highest score to the lowest score.

Requirements:

  • Start with this list: players = [("Alice", 1200), ("Bob", 4500), ("Charlie", 3200), ("Diana", 4500)]
  • Create a new list called leaderboard that is sorted by the score (the second element of the tuple) in descending order.
  • Ensure the original players list remains unchanged.
  • Use a lambda function as the key to target the score index.
# Your code here:
players = [("Alice", 1200), ("Bob", 4500), ("Charlie", 3200), ("Diana", 4500)]

# Create the sorted leaderboard list below
Rating
0 0

There are no comments for now.

to be the first to leave a comment.