Sorting objects of a user-definedclass 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 GFGclassGFG:def__init__(self,a,b):self.a=aself.b=bdef__repr__(self):returnstr((self.a,self.b))# List of objectsa=[GFG("geeks",1),GFG("computer",3),GFG("for",2),GFG("geeks",4),GFG("science",3)]res=sorted(a,key=lambdax:x.b)print(res)
Output[('geeks', 1), ('for', 2), ('computer', 3), ('science', 3), ('geeks', 4)]
Explanation:sorted()function sorts the list based on theb attribute of each object, using alambda function(lambda x: x.b) as the key argument. This ensures that the objects are compared and sorted according to theirb values in ascending order.
Using list.sort()
Thesort()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 GFGclassGFG:def__init__(self,a,b):self.a=aself.b=bdef__repr__(self):returnstr((self.a,self.b))# List of objectsa=[GFG("geeks",1),GFG("computer",3),GFG("for",2),GFG("geeks",4),GFG("science",3)]a.sort(key=lambdax: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 theb 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 theirb values.
using operator.attrgetter()
Theattrgetter()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.
Pythonfromoperatorimportattrgetter# User-defined class GFGclassGFG:def__init__(self,a,b):self.a=aself.b=bdef__repr__(self):returnstr((self.a,self.b))# List of objectsa=[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, usingattrgetter('b')as the key argument. Theattrgetter()function efficiently retrieves thebattribute for comparison, ensuring that the objects are sorted in ascending order of theirbvalues.
Using functools.cmp_to_key()
Thecmp_to_key() function from thefunctools 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.
Pythonfromfunctoolsimportcmp_to_key# User-defined class GFGclassGFG:def__init__(self,a,b):self.a=aself.b=bdef__repr__(self):returnstr((self.a,self.b))# List of objectsd=[GFG("geeks",1),GFG("computer",3),GFG("for",2),GFG("geeks",4),GFG("science",3)]defcompare(a,b):returna.b-b.bres=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 theb attribute using a customcompare() function withcmp_to_key(), which subtracts theb values to determine the order in ascending order.