Sort a list of objects in Python
This post will discuss how to sort a list of objects using an attribute in Python.
1. Using list.sort() function
A simple solution is to use the list.sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort.
It accepts two optional keyword-only arguments: key and reverse. The key argument specifies a single-arg function to extract a comparison key from each list object. When the reverse argument is True, the list will be sorted in reversed order.
To illustrate, the following sorts a list of Employee objects using the name attribute in the natural order, followed by the reverse order.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class Employee: def __init__(self, name, dept, age): self.name = name self.dept = dept self.age = age def __repr__(self): return '{' + self.name + ', ' + self.dept + ', ' + str(self.age) + '}' if __name__ == '__main__': employees = [ Employee('John', 'IT', 28), Employee('Sam', 'Banking', 20), Employee('Joe', 'Finance', 25) ] # sort list by `name` in the natural order employees.sort(key=lambda x: x.name) # output: [{Joe, Finance, 25}, {John, IT, 28}, {Sam, Banking, 20}] print(employees) # sort list by `name` in reverse order employees.sort(key=lambda x: x.name, reverse=True) # output: [{Sam, Banking, 20}, {John, IT, 28}, {Joe, Finance, 25}] print(employees) |
You can also use the operator.attrgetter() function to produce value for the key attribute. It returns a callable object that fetches a specified attribute from its operand.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
from operator import attrgetter class Employee: def __init__(self, name, dept, age): self.name = name self.dept = dept self.age = age def __repr__(self): return '{' + self.name + ', ' + self.dept + ', ' + str(self.age) + '}' if __name__ == '__main__': employees = [ Employee('John', 'IT', 28), Employee('Sam', 'Banking', 20), Employee('Joe', 'Finance', 25) ] employees.sort(key=attrgetter('name')) # output: [{Joe, Finance, 25}, {John, IT, 28}, {Sam, Banking, 20}] print(employees) |
2. Using sorted() function
The list.sort() function does not return the sorted sequence but modifies the list in-place. To return a new sorted list instance, you can use the sorted() built-in function. Like the list.sort() function, it accepts two optional keyword-only arguments – key and reverses – that have the same meaning. The following example demonstrates.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Employee: def __init__(self, name, dept, age): self.name = name self.dept = dept self.age = age def __repr__(self): return '{' + self.name + ', ' + self.dept + ', ' + str(self.age) + '}' if __name__ == '__main__': employees = [ Employee('John', 'IT', 28), Employee('Sam', 'Banking', 20), Employee('Joe', 'Finance', 25) ] sortedByName = sorted(employees, key=lambda x: x.name) # output: [{Joe, Finance, 25}, {John, IT, 28}, {Sam, Banking, 20}] print(sortedByName) |
That’s all about sorting a list of objects in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)