Quick answer: To sort a list of objects by attribute in Python, pass a key function to sorted() or list.sort():
sorted_people = sorted(people, key=lambda p: p.age)
That one line sorts a list of Person objects by their age attribute. In this guide you will learn every practical way to sort a list of objects by attribute in Python, including sorted(), sort(), operator.attrgetter, reverse order, multiple attributes, and how to make your own class sortable.
Python cannot compare two custom objects by default, so it needs to know which attribute to compare. The key argument tells it exactly that.
Table of Contents
- Example class used in this post
- Sort with sorted() and lambda
- Sort in place with list.sort()
- Sort with operator.attrgetter
- Sort in descending order
- Sort by multiple attributes
- Ascending and descending together
- Case-insensitive string sorting
- Handle None values
- Make objects sortable with __lt__
- Common errors
- FAQ
1. Example class used in this post
We will use a simple Person class with three attributes. A __repr__ method makes the printed output easy to read.
class Person:def __init__(self, name, age, salary):self.name = nameself.age = ageself.salary = salarydef __repr__(self):return f"Person({self.name!r}, {self.age}, {self.salary})"people = [Person("Ali", 30, 50000),Person("Sara", 25, 65000),Person("Zain", 35, 45000),Person("Hina", 25, 70000),]
2. Sort a list of objects with sorted() and lambda
The built-in sorted() function returns a new sorted list and leaves the original list unchanged. Use a lambda function as the key to choose the attribute:
sorted_people = sorted(people, key=lambda p: p.age)for p in sorted_people:print(p)
Output:
Person('Sara', 25, 65000)Person('Hina', 25, 70000)Person('Ali', 30, 50000)Person('Zain', 35, 45000)
Notice that Sara and Hina both have age 25 and keep their original order. Python's sort is stable, which means equal items are never reshuffled.
3. Sort in place with list.sort()
If you do not need the original order, use the sort() method. It changes the list itself and returns None:
people.sort(key=lambda p: p.salary)print(people)
Output:
[Person('Zain', 35, 45000), Person('Ali', 30, 50000), Person('Sara', 25, 65000), Person('Hina', 25, 70000)]
Common mistake: writing people = people.sort(...) sets people to None. Only sorted() returns a new list.
4. Sort with operator.attrgetter
The operator module offers attrgetter, a cleaner alternative to a lambda. It is also usually slightly faster on large lists.
from operator import attrgettersorted_people = sorted(people, key=attrgetter("age"))
This gives the same result as the lambda version, but the code reads more clearly: you simply name the attribute.
5. Sort in descending order
Add reverse=True to sort from highest to lowest:
sorted_people = sorted(people, key=attrgetter("salary"), reverse=True)for p in sorted_people:print(p)
Output:
Person('Hina', 25, 70000)Person('Sara', 25, 65000)Person('Ali', 30, 50000)Person('Zain', 35, 45000)
6. Sort by multiple attributes
To sort by more than one attribute, return a tuple from the key function. Python compares the first item, and only uses the second item when the first values are equal.
# Sort by age, then by namesorted_people = sorted(people, key=attrgetter("age", "name"))for p in sorted_people:print(p)
Output:
Person('Hina', 25, 70000)Person('Sara', 25, 65000)Person('Ali', 30, 50000)Person('Zain', 35, 45000)
Both people aged 25 are now ordered alphabetically: Hina comes before Sara.
7. Ascending and descending order together
For numeric attributes, put a minus sign in front of the value you want in descending order:
# Age ascending, salary descendingsorted_people = sorted(people, key=lambda p: (p.age, -p.salary))
This does not work for strings. To mix directions on string attributes, sort twice. Sort by the secondary key first, then by the primary key. Because Python's sort is stable, the order from the first pass is kept for ties:
people.sort(key=attrgetter("name"), reverse=True) # secondary keypeople.sort(key=attrgetter("age")) # primary key
8. Case-insensitive string sorting
By default, uppercase letters sort before lowercase letters, so "Zain" would come before "ali". To sort names without caring about case, lower-case the attribute in the key:
sorted_people = sorted(people, key=lambda p: p.name.lower())
9. Handle None values
If an attribute can be None, sorting raises a TypeError. Use a key that pushes None values to the end:
sorted_people = sorted(people,key=lambda p: (p.age is None, p.age or 0))
10. Make your objects sortable with __lt__
If you always sort objects the same way, define the comparison inside the class. Python's sorted() only needs the __lt__ (less than) method. The functools.total_ordering decorator fills in the other comparison methods for you:
from functools import total_ordering@total_orderingclass Person:def __init__(self, name, age, salary):self.name = nameself.age = ageself.salary = salarydef __eq__(self, other):return self.age == other.agedef __lt__(self, other):return self.age < other.agedef __repr__(self):return f"Person({self.name!r}, {self.age}, {self.salary})"people = [Person("Ali", 30, 50000), Person("Sara", 25, 65000)]print(sorted(people))
Output:
[Person('Sara', 25, 65000), Person('Ali', 30, 50000)]
Now you can call sorted(people) without a key. Use this approach only when one sort order is the natural default for the class. For everything else, a key function is more flexible.
11. Common errors and fixes
TypeError: '<' not supported between instances
TypeError: '<' not supported between instances of 'Person' and 'Person'
sorted(people) without a key, and the class has no __lt__ method.key=attrgetter("age") or define __lt__ in the class.AttributeError: 'Person' object has no attribute 'age'
getattr(p, "age", 0) in the key function to provide a default.Quick comparison
| Method | Changes original list? | Best for |
|---|---|---|
sorted(list, key=...) | No (returns new list) | Keeping the original order |
list.sort(key=...) | Yes (returns None) | Saving memory on large lists |
attrgetter("x") | Depends on how used | Clean, fast attribute sorting |
__lt__ in class | No | One default order for the class |
Frequently Asked Questions
How do I sort a list of objects by attribute in Python?
Use sorted(objects, key=lambda obj: obj.attribute) or sorted(objects, key=attrgetter("attribute")).
What is the difference between sorted() and sort()?
sorted() returns a new list and works on any iterable. sort() sorts the list in place, returns None, and only works on lists.
How do I sort objects in descending order?
Add reverse=True, for example sorted(people, key=attrgetter("age"), reverse=True).
How do I sort by two attributes in Python?
Return a tuple from the key function, such as attrgetter("age", "name") or lambda p: (p.age, p.name).
Is attrgetter faster than lambda?
Usually yes, slightly, because attrgetter is implemented in C. The difference only matters for very large lists.
Does this work with dataclasses?
Yes. A dataclass instance is a normal object, so sorted(items, key=attrgetter("field")) works the same way. You can also pass order=True to @dataclass to make instances sortable by their fields in order.
Conclusion
To sort a list of objects by attribute in Python, use sorted() or list.sort() with a key function. Use a lambda for quick jobs, attrgetter for
