Open In App

Sorting Objects of User Defined Class in Python

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting objects of a user-defined class in Python involves arranging instances of the class based on the values of one or more of their attributes. For example, if we have a class Person with attributes like name and age, we might want to sort a list of Person objects based on the age attribute to organize them from youngest to oldest.

Using sorted()

sorted() function returns a new sorted list, leaving the original list unchanged. By providing a key argument, we can specify a function to extract a value used for comparison during sorting.

Python
# User-defined class GFG
class GFG:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return str((self.a, self.b))

# List of objects
a = [GFG("geeks", 1),
     GFG("computer", 3),
     GFG("for", 2),
     GFG("geeks", 4),
     GFG("science", 3)]
     
res = sorted(a , key=lambda x: x.b)
print(res)

Output
[('geeks', 1), ('for', 2), ('computer', 3), ('science', 3), ('geeks', 4)]

Explanation: sorted() function sorts the list based on the b attribute of each object, using a lambda function (lambda x: x.b) as the key argument. This ensures that the objects are compared and sorted according to their b values in ascending order.

Using list.sort()

The sort() method sorts a list in place, meaning the original list is modified. It is slightly more efficient than sorted() when the goal is to modify the list itself.

Python
# User-defined class GFG
class GFG:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return str((self.a, self.b))

# List of objects
a  = [GFG("geeks", 1),
      GFG("computer", 3),
      GFG("for", 2),
      GFG("geeks", 4),
      GFG("science", 3)]

a.sort(key=lambda x: x.b)
print(a)

Output
[('geeks', 1), ('for', 2), ('computer', 3), ('science', 3), ('geeks', 4)]

Explanation: sort() method sorts the list in place based on the b attribute of each object, using a lambda function (lambda x: x.b) as the key argument. This modifies the original list, arranging the objects in ascending order of their b values.

using operator.attrgetter()

The attrgetter() function from the operator module is used to retrieve the value of an attribute. It's a more efficient way of specifying the key function compared to a lambda function.

Python
from operator import attrgetter
# User-defined class GFG
class GFG:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return str((self.a, self.b))

# List of objects
a = [GFG("geeks", 1),
       GFG("computer", 3),
       GFG("for", 2),
       GFG("geeks", 4),
       GFG("science", 3)]


res = sorted(a, key=attrgetter('b'))
print(res)

Output
[('geeks', 1), ('for', 2), ('computer', 3), ('science', 3), ('geeks', 4)]

Explanation: sorted() sorts the list based on the b attribute of each object, using attrgetter('b') as the key argument. The attrgetter() function efficiently retrieves the b attribute for comparison, ensuring that the objects are sorted in ascending order of their b values.

Using functools.cmp_to_key()

The cmp_to_key() function from the functools module allows using a comparison function instead of a key function. While more versatile, this method can be less efficient due to the overhead of comparison operations.

Python
from functools import cmp_to_key

# User-defined class GFG
class GFG:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return str((self.a, self.b))

# List of objects
d = [GFG("geeks", 1),
       GFG("computer", 3),
       GFG("for", 2),
       GFG("geeks", 4),
       GFG("science", 3)]

def compare(a, b):
    return a.b - b.b

res = sorted(d, key=cmp_to_key(compare))
print(res)

Output
[('geeks', 1), ('for', 2), ('computer', 3), ('science', 3), ('geeks', 4)]

Explanation: sorted() function sorts the list based on the b attribute using a custom compare() function with cmp_to_key(), which subtracts the b values to determine the order in ascending order.


Next Article

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy