Sorting Objects in Python. Sorting Objects of the same Class | by Sadrach Pierre, Ph.D. | Towards Data Science

In computer science, classes are blueprints for defining objects with related attributes and methods. A common task in computer science is sorting data structures based on attributes. In this post, we will discuss how to sort objects of the same class based on attribute values.
Let’s get started!
Suppose we have a class called ‘AppleMusicUser’, with an ‘__init__’ method that initializes an apple user ID:
class AppleMusicUser:    def __init__(self, apple_id):        self.apple_id = apple_id
Let’s create an instance of our ‘AppleMusicUser’ class with the email ‘emusk@tesla.com’:
user1 = AppleMusicUser("emusk@tesla.com")
If we print this object we get:
print(user1)
Which says the ‘AppleMusicUser’ object is located at the specified memory address. We can change how this object is represented by adding a ‘__repr__’ method:
class AppleMusicUser:    def __init__(self, apple_id):        self.apple_id = apple_id    def __repr__(self):        return 'AppleID({})'.format(self.apple_id)
Now if we print:
print(user1)
Next, suppose we have a list of ‘AppleMusicUser’ objects:
users = [AppleMusicUser("mzuckerberg@facebook.com"), AppleMusicUser("jdorsey@twitter.com"), AppleMusicUser("emusk@tesla.com")]
Let’s print the list of objects:
print(users)
We can sort the list of objects according to the apple ID using the ‘sorted()’ method and a lambda function:
print(sorted(users, key = lambda u: u.apple_id))
Alternatively, we can use the ‘attrgetter()’ method in the operator module to define the key in our sorted method:
from operator import attrgetterprint(sorted(users, key = attrgetter('appled_id')))
I personally prefer using ‘attrgetter()’ to define the sorting key but using the lambda function also works well. The advantages of using ‘attrgetter()’ are in speed and the ability to pull more than one attribute.
For our last example, suppose we have an additional attribute, ‘plays’ , corresponding to the number of songs played:
class AppleMusicUser:    def __init__(self, apple_id, plays):        self.apple_id = apple_id        self.plays = plays     def __repr__(self):        return 'AppleID({}, plays:{})'.format(self.apple_id, self.plays)
Let’s redefine our list of objects:
users = [AppleMusicUser("mzuckerberg@facebook.com", 100), AppleMusicUser("jdorsey@twitter.com", 20),          AppleMusicUser("emusk@tesla.com", 50)]print(users)
We can sort the objects according to the number of plays:
from operator import attrgetterprint(sorted(users, key = attrgetter('plays')))
I’ll stop here but feel free to play around with the code yourself.
To summarize, in this post we discussed how to sort objects in python. First we showed how to sort objects corresponding to instances of the ‘AppleMusicUser’ class according to the attribute ‘apple_id’ using the sorted method and a lambda function. Next, we showed how to perform the same sorting task by using the ‘attrgetter’ method in the operator module. Finally, we showed how to sort according to an additional attribute corresponding to the number of songs played by the user. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!