How to sort a list in Python
Learn how to sort a list in Python. Explore different methods, tips, real-world applications, and how to debug common sorting errors.

For any developer, it's essential to know how to sort a list in Python. The language offers powerful built-in functions, like sorted(), that simplify this common task.
In this article, you'll explore several techniques and practical tips for effective data arrangement. You will also find real-world applications and specific debugging advice to help you master list manipulation in your projects.
Basic list sorting with sort() method
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers)--OUTPUT--[1, 2, 5, 8, 9]
The sort() method is an in-place operation, which means it modifies the list directly instead of creating a new one. This approach is memory-efficient because it avoids making a copy. You'll notice sort() returns None—a common Python convention for functions that mutate objects directly.
- This makes it a great choice when you don't need to preserve the original order of the list.
- It's also particularly useful when working with large datasets where minimizing memory consumption is a priority.
Common sorting techniques
While the sort() method modifies a list in place, other techniques offer more flexibility, like creating a new sorted list or defining custom rules.
Sorting with the sorted() function
original = [5, 2, 8, 1, 9]
sorted_list = sorted(original)
print("Original:", original)
print("Sorted:", sorted_list)--OUTPUT--Original: [5, 2, 8, 1, 9]
Sorted: [1, 2, 5, 8, 9]
Unlike the sort() method, the sorted() function returns a new sorted list, leaving the original one untouched. This is incredibly useful when you need to work with a sorted version of your data while preserving the original sequence for other parts of your program.
- Because
sorted()creates a new list, it's the perfect choice when the original order is important. - This function isn't limited to lists; you can use it on any iterable, like tuples or strings.
Sorting in reverse order
numbers = [5, 2, 8, 1, 9]
numbers.sort(reverse=True)
print(numbers)--OUTPUT--[9, 8, 5, 2, 1]
For descending order, both the sort() method and sorted() function accept a reverse parameter. When you set reverse=True, the list is arranged from the largest element to the smallest.
- This simple boolean flag flips the default ascending sort, giving you quick control over the order.
- It’s a straightforward way to get a reversed sequence, whether you're modifying the list in-place or creating a new one.
Sorting with custom keys
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
fruits.sort(key=len)
print(fruits)--OUTPUT--['date', 'apple', 'cherry', 'banana', 'elderberry']
The key parameter lets you specify a function to be called on each list element before making comparisons. In this example, using key=len tells Python to sort the list of strings based on their length instead of their alphabetical order. The sorting algorithm uses the return value of this key function to determine the final arrangement.
- This offers incredible flexibility, allowing you to sort complex objects based on a specific attribute or use a
lambdafunction for more intricate logic. - The
keyparameter works with both thesort()method and thesorted()function.
Advanced sorting approaches
Beyond simple key functions, you can implement more advanced sorting logic with lambda functions, functools.cmp_to_key, and specialized tools from the operator module.
Sorting with lambda functions
people = [("Alice", 25), ("Bob", 19), ("Charlie", 32)]
people.sort(key=lambda x: x[1])
print(people)--OUTPUT--[('Bob', 19), ('Alice', 25), ('Charlie', 32)]
A lambda function is a compact, anonymous function you can define on the fly. In this case, key=lambda x: x[1] instructs the sort to use the second element of each tuple—the age—as the sorting criterion. The list is then reordered based on the values returned by this lambda for each item.
- This approach is perfect for simple, one-off operations where defining a full, separate function would be overkill.
- It allows you to embed custom logic directly within the
sort()method call, making your code more concise and ideal for vibe coding.
Sorting with functools.cmp_to_key
from functools import cmp_to_key
def compare(a, b):
return a % 10 - b % 10 # Sort by last digit
numbers = [15, 32, 48, 27, 91]
sorted_numbers = sorted(numbers, key=cmp_to_key(compare))
print(sorted_numbers)--OUTPUT--[91, 32, 15, 27, 48]
The functools.cmp_to_key utility converts an older-style comparison function into a key that modern sorting methods can use. You'll find it helpful when your logic requires directly comparing two elements, a and b, instead of just evaluating a single attribute.
- The custom
comparefunction here dictates the order based on the last digit of each number, which is found using the modulo operator (%). - Its return value—negative, zero, or positive—tells the sort algorithm which element should come first, offering precise control over the final sequence.
Sorting with the operator module
import operator
students = [{"name": "Alice", "grade": 85}, {"name": "Bob", "grade": 92}, {"name": "Charlie", "grade": 78}]
sorted_students = sorted(students, key=operator.itemgetter("grade"), reverse=True)
print(sorted_students)--OUTPUT--[{'name': 'Bob', 'grade': 92}, {'name': 'Alice', 'grade': 85}, {'name': 'Charlie', 'grade': 78}]
The operator module provides a clean and efficient alternative to lambda functions for common key operations. Instead of writing a lambda, you can use operator.itemgetter("grade"). This creates a function that specifically fetches the value associated with the "grade" key from each dictionary in the list.
- This approach is often faster and considered more readable, especially when your sorting logic is straightforward.
- It's perfect for sorting complex data structures like lists of dictionaries or objects by a specific field.
Move faster with Replit
Replit is an AI-powered development platform where you can start coding Python instantly. It comes with all the necessary dependencies pre-installed, so you can skip the tedious setup and environment configuration.
While mastering functions like sort() is essential, you can move from piecing together techniques to building complete applications with Agent 4. It takes your idea and builds a working product—handling the code, databases, APIs, and deployment directly from a description.
- A price comparison tool that sorts a list of products by price or rating.
- A file organizer that sorts files in a directory by their size or modification date.
- A project management dashboard that organizes tasks first by priority level, then alphabetically.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with powerful tools, you might encounter a few common pitfalls when sorting lists in Python.
Dealing with TypeError when sorting mixed types
A TypeError often appears when you try to sort a list containing mixed data types, like numbers and strings. Python can't compare these different types directly, so it raises an error. To fix this, you can either ensure all items in your list are of a single, comparable type or use a key function to convert them to a common format—like using key=str to treat every element as a string during the sort.
Handling the AttributeError with immutable sequences
You'll run into an AttributeError if you attempt to use the sort() method on an immutable sequence, such as a tuple. Because tuples cannot be changed, they don't have a sort() method, which modifies a list in-place. The solution is to use the sorted() function instead, as it returns a new sorted list and leaves the original tuple untouched.
Handling dictionaries with missing key values
When sorting a list of dictionaries, you might get a KeyError if the key you're sorting by doesn't exist in every dictionary. You can prevent this by using the dictionary's get() method within your key function. For example, key=lambda x: x.get('my_key', 0) provides a default value of 0 for any dictionary missing 'my_key', ensuring the sort operation completes without errors.
Dealing with TypeError when sorting mixed types
Python's sorting functions require a consistent way to compare every item in a list. When you mix incompatible types, like numbers and strings, the interpreter doesn't know how to determine which comes first, triggering a TypeError. The code below demonstrates this issue.
mixed_list = [5, "apple", 10, "banana", 2]
mixed_list.sort()
print(mixed_list)
This code triggers a TypeError because the sort() method doesn't know how to compare a number like 5 with a string like "apple". You can resolve this by giving the sort a consistent format to work with.
mixed_list = [5, "apple", 10, "banana", 2]
numbers = sorted([x for x in mixed_list if isinstance(x, int)])
strings = sorted([x for x in mixed_list if isinstance(x, str)])
result = numbers + strings
print(result)
The solution works by separating the mixed list into two distinct lists—one for numbers and one for strings. It uses list comprehensions with isinstance() to filter the items by type. Each new list is then sorted independently before they are combined.
- This strategy is effective when you need to group items by type before sorting, a common challenge when processing data from files or APIs where types can be inconsistent. Consider using automated testing to catch these edge cases early.
Handling the AttributeError with immutable sequences
The AttributeError is a common roadblock when you try to modify data that can't be changed, like a tuple. Since the sort() method alters a list directly, it doesn't exist for immutable types. The following code demonstrates this common mistake.
data_tuple = (5, 2, 8, 1, 9)
data_tuple.sort()
print(data_tuple)
This code calls the sort() method on a tuple, which triggers the error. Since tuples can't be changed, they don't have an in-place sort() method. Check out the correct way to handle this.
data_tuple = (5, 2, 8, 1, 9)
sorted_data = sorted(data_tuple)
print(sorted_data)
sorted_tuple = tuple(sorted(data_tuple))
print(sorted_tuple)
The solution is to use the sorted() function, which works on any iterable—including immutable ones like tuples. It returns a new sorted list, leaving your original tuple unchanged. This approach is essential whenever you're working with data you can't modify directly.
- If you need the final result to be a tuple, you can simply convert the sorted list back using the
tuple()constructor.
Handling dictionaries with missing key values
Sorting a list of dictionaries is straightforward until you hit one that's missing the key you're sorting by. This common issue will stop your code with a KeyError. The example below shows what happens when a dictionary is missing the "grade" key.
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob"}, # Missing "grade" key
{"name": "Charlie", "grade": 78}
]
students.sort(key=lambda x: x["grade"])
print(students)
The code fails because the lambda function tries to access x["grade"] on a dictionary where that key doesn't exist, raising a KeyError. Take a look at how to prevent this with a more robust approach.
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob"}, # Missing "grade" key
{"name": "Charlie", "grade": 78}
]
students.sort(key=lambda x: x.get("grade", 0))
print(students)
The solution uses the dictionary’s get() method to provide a fallback. Instead of crashing, key=lambda x: x.get("grade", 0) assigns a default value of 0 to any dictionary missing the "grade" key. This ensures the sort operation can complete without a KeyError.
- You'll find this approach essential when working with data from APIs or files where certain fields might be optional, making your code more resilient.
Real-world applications
After mastering the methods and troubleshooting common errors, you can apply sorting to build practical, real-world applications.
Sorting files by modification date with os.path.getmtime()
You can automate tasks like organizing a directory by using os.path.getmtime() as a sort key to arrange files based on their last modification date.
import os
from datetime import datetime
files = os.listdir('.')
files.sort(key=lambda x: os.path.getmtime(x))
for file in files[:3]: # Print first 3 files (oldest)
mod_time = datetime.fromtimestamp(os.path.getmtime(file))
print(f"{file}: {mod_time.strftime('%Y-%m-%d %H:%M:%S')}")
This script demonstrates a practical way to find the oldest files in your current directory. It uses os.listdir('.') to gather all file and directory names into a list. This list is then sorted in-place, arranging the items chronologically from oldest to newest based on their last modification time.
- The final
forloop processes only the first three items from the sorted list. - It uses the
datetimemodule to convert each file's raw modification timestamp into a clean, human-readable date and time before printing it.
Creating a leaderboard with multiple sorted() criteria
You can create complex sorting logic, like a leaderboard that ranks players by score and then by time, by returning a tuple from your key function.
players = [
{"name": "Alice", "score": 192, "time": 45.2},
{"name": "Bob", "score": 192, "time": 39.8},
{"name": "Charlie", "score": 156, "time": 42.1},
{"name": "Diana", "score": 218, "time": 38.6}
]
# Sort by score (descending) and time (ascending) for ties
leaderboard = sorted(players, key=lambda x: (-x["score"], x["time"]))
for rank, player in enumerate(leaderboard, 1):
print(f"{rank}. {player['name']}: {player['score']} pts ({player['time']}s)")
This snippet demonstrates a powerful technique for multi-level sorting. The key argument is given a lambda function that produces a tuple for each player: (-x["score"], x["time"]). Python's sorting algorithm compares these tuples from left to right.
- The first element, the negative score, cleverly forces a descending order for scores.
- When scores are identical, the second element,
time, is used as a tiebreaker, sorting players by their completion time in ascending order.
The final loop uses enumerate() to add a numerical rank to each player, creating the formatted leaderboard output.
Get started with Replit
Now, turn your knowledge of sorting into a real tool with Replit Agent. Describe what you want to build, like “a file organizer that sorts by size” or “a price comparison tool that sorts by rating.”
Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



