How to sort a list of objects in Python
Learn how to sort a list of objects in Python. Explore different methods, tips, real-world examples, and common error debugging.

Sorting a list of objects in Python is a common task for developers who need to organize complex data structures. Python’s built-in tools offer powerful ways to handle this with precision.
In this article, you'll learn key techniques and tips for sorting objects. You'll explore real-world applications and debugging advice to help you master this essential skill for your projects.
Sorting a list using the sort() method
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers)--OUTPUT--[1, 2, 5, 8, 9]
The sort() method is a straightforward way to organize lists directly. When you call numbers.sort(), you're not creating a new list; you're modifying the original numbers list in place. This is a key distinction because the method itself returns None, permanently altering the list it's called on.
By default, it sorts in ascending order. A common mistake is assigning the result to a new variable, which would result in None. Always remember that sort() is an in-place operation.
Sorting with key functions
To go beyond simple sorting, the key parameter allows you to specify exactly how Python should organize more complex objects and data structures.
Using the key parameter with a lambda function
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda student: student[1], reverse=True)
print(students)--OUTPUT--[('Bob', 92), ('Alice', 85), ('Charlie', 78)]
A lambda function provides a quick, inline way to specify your sorting criteria with the key parameter. Instead of defining a separate function, you can create a simple one on the fly. This is perfect for sorting by a specific element in a more complex data structure, like a tuple.
- The expression
key=lambda student: student[1]tells Python to use the second element of each tuple (the score) for comparison. - Adding
reverse=Trueflips the order, sorting the list from highest score to lowest.
Using sorted() function to create a new sorted list
fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits, key=len)
print(sorted_fruits)--OUTPUT--['date', 'apple', 'banana', 'cherry']
Unlike the sort() method, the sorted() function returns a new, sorted list while leaving the original untouched. This is perfect for when you need to preserve the initial order of your data for other operations.
- In this case,
key=leninstructs the function to sort the strings by their length. - The result is a new list,
sorted_fruits, organized from the shortest string to the longest, while the originalfruitslist remains unchanged.
Sorting objects by multiple attributes
people = [("Alice", 25), ("Bob", 30), ("Charlie", 25)]
people.sort(key=lambda person: (person[1], person[0]))
print(people)--OUTPUT--[('Alice', 25), ('Charlie', 25), ('Bob', 30)]
When a single sorting criterion isn't enough, you can provide a tuple to the key parameter to define a sequence of sorting rules. Python will use the elements in the tuple as primary, secondary, and subsequent sorting keys to resolve any ties.
- The expression
key=lambda person: (person[1], person[0])first sorts the list by age (the second element of each tuple). - If two people have the same age, it uses their name (the first element) as a tie-breaker, sorting them alphabetically.
This is why Alice appears before Charlie in the output. They're both 25, so Python uses their names to determine their final order.
Advanced sorting techniques
As your data structures become more intricate, you'll need more than simple lambda functions—Python’s advanced tools give you precise control over sorting.
Sorting with operator module functions
import operator
books = [{"title": "Python Basics", "pages": 250}, {"title": "Advanced Python", "pages": 400}]
sorted_books = sorted(books, key=operator.itemgetter("pages"))
print(sorted_books)--OUTPUT--[{'title': 'Python Basics', 'pages': 250}, {'title': 'Advanced Python', 'pages': 400}]
For a cleaner and often faster approach than lambda, you can use the operator module. It's particularly useful when you need to access elements by their key or index.
- The function
operator.itemgetter("pages")does exactly what it sounds like—it creates a callable that retrieves the value for the "pages" key from each dictionary in the list. - This results in more readable code when your sorting logic is a simple lookup.
Sorting with custom classes and __lt__ method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
people = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 22)]
people.sort()
print(people)--OUTPUT--[Person('Charlie', 22), Person('Alice', 25), Person('Bob', 30)]
You can give your custom objects a default sorting behavior by defining how they compare to one another. This is done by implementing the special __lt__ method, which stands for "less than." When Python's sort() method doesn't have a key to work with, it falls back on __lt__ to determine the order.
- In this class, the expression
return self.age < other.agetells Python that one person is "less than" another if their age is lower. - This embeds the sorting logic directly into the
Personclass itself.
Implementing stable sorting with functools.cmp_to_key
from functools import cmp_to_key
def compare_grades(a, b):
if a["grade"] == b["grade"]:
return 0
return -1 if a["grade"] > b["grade"] else 1
students = [{"name": "Alice", "grade": "B"}, {"name": "Bob", "grade": "A"}, {"name": "Charlie", "grade": "B"}]
sorted_students = sorted(students, key=cmp_to_key(compare_grades))
print(sorted_students)--OUTPUT--[{'name': 'Bob', 'grade': 'A'}, {'name': 'Alice', 'grade': 'B'}, {'name': 'Charlie', 'grade': 'B'}]
The functools.cmp_to_key function is a bridge to an older style of sorting. It converts a comparison function—like compare_grades—into a key that sorted() can use. This approach is handy for complex sorting logic where you need to compare two items directly against each other.
- Your comparison function should return
-1if the first item comes before the second,1if it comes after, and0if they're equal. - Python's sort is stable, which means items that compare as equal (like Alice and Charlie) will keep their original relative order in the sorted list.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of piecing together techniques, you can use Agent 4 to build complete apps. It takes an idea to a working product by handling the code, databases, APIs, and deployment, directly from a description.
Instead of manually combining sorting functions like sorted(), you can describe the final tool you need, and Agent will build it. For instance, you could create:
- A customer support dashboard that sorts tickets first by priority level, then by the date they were submitted.
- A leaderboard generator that organizes players from a list of dictionaries by their score in descending order.
- An e-commerce inventory tool that sorts a list of products by stock quantity to quickly see what needs restocking.
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 Python's powerful tools, you might run into a few common roadblocks when sorting objects, but they're all manageable with the right approach.
Fixing TypeError when sorting lists with mixed types
A TypeError is one of the most frequent issues. It pops up when you try to sort a list containing items that can't be compared with each other, like numbers and strings.
- The Cause: Python doesn't know how to decide if
5is "less than""five", so it raises an error. This often happens with messy data where a list contains mixed data types. - The Fix: Ensure all items in your list are of a comparable type. If you're sorting objects, use a
keyfunction to specify an attribute that has a consistent data type across all objects.
Handling AttributeError when using .sort() on immutable sequences
You'll encounter an AttributeError if you try to use the .sort() method on an immutable data type, such as a tuple.
- The Cause: The
.sort()method modifies a list in-place, but immutable objects cannot be changed after they're created. Since tuples are immutable, they don't have a.sort()method. - The Fix: Use the built-in
sorted()function instead. It works on any iterable—including tuples—and returns a new, sorted list without altering the original.
Resolving KeyError when sorting dictionaries with missing keys
When sorting a list of dictionaries, a KeyError can stop your code in its tracks if a dictionary is missing the sort key.
- The Cause: If your
keyfunction tries to access a dictionary key that doesn't exist in one of the dictionaries, Python will raise this error. - The Fix: A robust solution is to use the dictionary's
.get()method within your key function. For example,key=lambda x: x.get("my_key", 0)provides a default value if"my_key"is missing, preventing the error and allowing the sort to complete.
Fixing TypeError when sorting lists with mixed types
You'll hit a TypeError when trying to sort a list with incompatible data types, such as integers and strings. Python raises this error because it can't determine if a number is "less than" a word. See what happens in the example below.
mixed_list = [1, "apple", 3, "banana"]
mixed_list.sort()
print(mixed_list)
The sort() method fails when it attempts to compare the integer 1 with the string "apple", which triggers the TypeError. The following code demonstrates how to resolve this by making the elements comparable.
mixed_list = [1, "apple", 3, "banana"]
sorted_list = sorted(mixed_list, key=str)
print(sorted_list)
The solution works by making all elements comparable. Using key=str tells the sorted() function to temporarily treat each item as a string for the comparison. This resolves the TypeError because Python can now sort values like 1 and "apple" alphabetically as "1" and "apple". You'll often encounter this issue when working with data from external sources, like APIs or user input, where data types can be inconsistent.
Handling AttributeError when using .sort() on immutable sequences
Handling AttributeError when using .sort() on immutable sequences
An AttributeError appears when you try to modify something that can't be changed, like a tuple. The .sort() method alters a list in-place, but since tuples are immutable, they don't have this method. See what happens when you try.
numbers = (5, 2, 8, 1, 9) # This is a tuple
numbers.sort()
print(numbers)
The AttributeError happens because the code calls .sort() on a tuple. This method is designed to modify a list in-place, so it doesn't exist for unchangeable data types like tuples. See the correct approach below.
numbers = (5, 2, 8, 1, 9) # This is a tuple
sorted_numbers = sorted(numbers)
print(sorted_numbers)
The fix is to use the sorted() function, which works on any iterable—including tuples. It returns a new, sorted list and leaves the original tuple untouched. This is the correct approach for immutable data types that can't be changed in-place. You'll often run into this error when working with data structures where you aren't sure if you have a list or a tuple, so using sorted() is a safer bet.
Resolving KeyError when sorting dictionaries with missing keys
Resolving KeyError when sorting dictionaries with missing keys
A KeyError occurs when you sort a list of dictionaries by a key that doesn't exist in every item. This is common with inconsistent data where some dictionaries are missing expected fields. See what happens when the code encounters a missing key.
data = [{"id": 1, "score": 85}, {"id": 2}, {"id": 3, "score": 90}]
data.sort(key=lambda x: x["score"])
print(data)
The KeyError is triggered because the lambda function can't find the score key in the second dictionary. The sort operation halts immediately. See how to resolve this in the following example.
data = [{"id": 1, "score": 85}, {"id": 2}, {"id": 3, "score": 90}]
data.sort(key=lambda x: x.get("score", 0))
print(data)
The fix uses the dictionary’s .get() method to prevent a KeyError. By using key=lambda x: x.get("score", 0), you tell Python to use a default value of 0 whenever the "score" key is missing. This allows the sort to complete without crashing. You'll find this technique essential when working with data from APIs or databases, where records might not always have a consistent structure.
Real-world applications
Beyond fixing errors, these sorting methods are the backbone of features you use daily, from e-commerce sites to navigation apps.
Sorting e-commerce products by customer rating
Displaying products from highest to lowest customer rating is a common feature that helps shoppers quickly identify the best-reviewed items.
products = [
{"name": "Headphones", "rating": 4.7, "price": 99.99},
{"name": "Bluetooth Speaker", "rating": 4.2, "price": 59.99},
{"name": "Wireless Mouse", "rating": 4.9, "price": 39.99}
]
products.sort(key=lambda x: x["rating"], reverse=True)
print(products)
This example demonstrates how to reorder a list of dictionaries in-place. The sort() method directly modifies the products list, arranging its items based on a specific criterion.
- The
keyparameter is given alambdafunction,lambda x: x["rating"], which instructs the sort to use each dictionary's"rating"value for comparison. - Setting
reverse=Trueensures the final order is descending, from the largest rating value to the smallest.
This technique is efficient for organizing complex data without creating a new list.
Finding nearby locations by sorting with a distance key
You can also use a custom function as the key to sort items based on more complex logic, such as calculating the distance between geographic points.
import math
def distance(point, reference):
return math.sqrt((point[0] - reference[0])**2 + (point[1] - reference[1])**2)
locations = [("Store A", 3, 4), ("Store B", 1, 2), ("Store C", 5, 1)]
reference_point = (0, 0)
sorted_locations = sorted(locations, key=lambda loc: distance((loc[1], loc[2]), reference_point))
print(sorted_locations)
This snippet sorts a list of locations based on their proximity to a `reference_point`. It’s a powerful example of combining a custom function with a `lambda` for more advanced sorting logic.
- The custom `distance` function calculates the straight-line distance between two coordinates.
- The `sorted()` function then uses a `lambda` as its `key`, which calls the `distance` function for each location in the list.
The returned distance from the function is used as the value for comparison, creating a new list ordered from nearest to farthest from the origin point.
Get started with Replit
Now, turn your knowledge into a real tool. Describe what you want to Replit Agent, like "Build a tool that sorts a CSV of user data by last login date" or "Create a script that organizes a list of files by size."
Replit Agent handles the entire process—it writes the code, tests for errors, and deploys your app. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)

.png)