Sort List of Objects in Python

We can sort a list of numbers simply using the sort() method or the sorted() function. However, we cannot do so with a list of objects created using custom classes. In this article, we will discuss how we can sort a list of objects using the sort() method and the sorted() function in python.

How to Sort a List of Objects in Python?

Normally, when we have a list of numbers, we can sort this using the sort() method as shown below.

myList = [1, 2, 9, 3, 6, 17, 8, 12, 10]
print("Original list is:", myList)
myList.sort()
print("The sorted list is:", myList)

Output:

Original list is: [1, 2, 9, 3, 6, 17, 8, 12, 10]
The sorted list is: [1, 2, 3, 6, 8, 9, 10, 12, 17]

Now, let us try to sort a list of objects. For this, we will create a Person class will attributes name and age. After that, we will create different person objects and make a list consisting of the objects. When we try to sort the list, the program will run into the TypeError exception as shown below.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name


person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)

myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
    print(person, end=",")
print("n")
myList.sort()
print("The sorted list is:", myList)

Output:

Original list is:
Sam,Harry,Tom,John,Kite,Emily,

/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 22, in <module>
    myList.sort()
TypeError: '<' not supported between instances of 'Person' and 'Person'

The error has occurred here because we cannot compare two Person objects using the < operator. So, we will have to specify an attribute of the Person class that will be used to compare two different Person objects. For this, we use the “key” parameter in the sort() method.

We will first create a function getAge() that accepts a Person object as an input argument and returns the age.

After that, we will assign the getAge() function to the key parameter. After execution, the sort() method will sort the list of Person objects as shown in the following example.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name


def getAge(person):
    return person.age


person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)

myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
    print(person, end=",")
print("n")
myList.sort(key=getAge)
print("The sorted list is:")
for person in myList:
    print(person, end=",")

Output:

Original list is:
Sam,Harry,Tom,John,Kite,Emily,

The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,

If you are not allowed to modify the input list, you can use the sorted() function to sort the list of objects. Here, we will pass the list of objects as the first input argument and the getAge() function as the second input argument. After execution, it will return a sorted list of the objects as shown below.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name


def getAge(person):
    return person.age


person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)

myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
    print(person, end=",")
print("n")
newList = sorted(myList, key=getAge)
print("The sorted list is:")
for person in newList:
    print(person, end=",")

Output:

Original list is:
Sam,Harry,Tom,John,Kite,Emily,

The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,

Sort a List of Objects Using Lambda Function

Instead of defining a different function such as getAge(), we can use the lambda function to sort the list of objects. Here, we will create a lambda function that takes an object and returns its attribute. Then, we will assign the lambda function to the parameter key in the sort() method. After execution of the sort() method, the list will get sorted as you can observe in the following example.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name


person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)

myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
    print(person, end=",")
print("n")
myList.sort(key=lambda p: p.age)
print("The sorted list is:")
for person in myList:
    print(person, end=",")

Output:

Original list is:
Sam,Harry,Tom,John,Kite,Emily,

The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,

Instead of the sort() method, you can also use the sorted() function with the lambda function to sort a list of objects as shown in the following example.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name


person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)

myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
    print(person, end=",")
print("n")
newList = sorted(myList, key=lambda p: p.age)
print("The sorted list is:")
for person in newList:
    print(person, end=",")

Output:

Original list is:
Sam,Harry,Tom,John,Kite,Emily,

The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,

Conclusion

In this article, we have discussed how to sort a list of objects in python. To know more about lists in python, you can read this article on list comprehension in python.

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Leave a Comment