Open In App

Sorting objects of user defined class in Python

Last Updated : 29 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The following article discusses how objects of a user-defined class can be arranged based on any of the variables of the class, which obviously will hold some value for every object. So far, we are aware of how we can sort elements of a list, the concept here is more or less the same as, except it is a step forward or we can say it is an advanced version of sorting elements but instead of a list we are dealing with objects of a class. 

Here sorted() method will be used. 

Syntax:

sorted (iterable, key(optional), reverse(optional) )

Example: This is just a generic example to show how this method is employed

Python3




print(sorted([1,26,3,9]))
  
print(sorted("Geeks foR gEEks".split(), key=str.lower))


Output:

[1, 3, 9, 26]
['foR', 'Geeks', 'gEEks']

Sorting objects of User Defined Class

Method 1:

In order to sort objects of a user-defined class, a key needs to be set for the sorted method, such that the key will be an indicator of how the objects should be sorted. With reference to the examples given below, here a function has been provided to the key which one by one compares the specified variable value for each object and returns a sorted list of objects for a class.

Example 1: Sorting elements in ascending order of the integer value given to them

Python3




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
gfg = [GFG("geeks", 1),
       GFG("computer", 3),
       GFG("for", 2),
       GFG("geeks", 4),
       GFG("science", 3)]
  
# sorting objects on the basis of value 
# stored at variable b
print(sorted(gfg, key=lambda x: x.b))


Output:

[(‘geeks’, 1), (‘for’, 2), (‘computer’, 3), (‘science’, 3), (‘geeks’, 4)]

Example 2: Sorting objects on the basis of the string value a variable holds

Python3




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
gfg = [GFG("geeks", 1),
       GFG("computer", 3),
       GFG("for", 2),
       GFG("geeks", 4),
       GFG("science", 3)]
  
# sorting objects on the basis of value 
# stored at variable a
print(sorted(gfg, key=lambda x: x.a.lower()))


Output:

[(‘computer’, 3), (‘for’, 2), (‘geeks’, 1), (‘geeks’, 4), (‘science’, 3)]

Method 2:

This method depicts how objects of a user-defined class can be sorted using functools inbuilt method total_ordering as a decorator to the class. Here, the class is defined normally as done in the above examples, only difference being during sorting, total_ordering() decorator is used. Two requirements for using total_ordering() are-

  • Out of less than(__lt__), greater than(__gt__), less than equal to(__le__) and greater than equal to(__ge__), atleast one should be defined in the class being decorated using this method.
  • Equal to (__eq__) should be defined.

In the example given below less than and greater than, both are defined even though during processing only one is called(in this less than) since one is enough to decide the order of the elements but it is good programming practice to define all in case one thing fails. During sorting one of the comparison methods are called to compare objects on the basis of some element and the sorted result is returned.

Example:

Python3




import functools
from functools import total_ordering
  
  
@total_ordering
class GFG:
    print("inside class")
  
    def __init__(self, a, b):
        self.a = a
        self.b = b
  
    def __lt__(self, obj):
        return ((self.b) < (obj.b))
  
    def __gt__(self, obj):
        return ((self.b) > (obj.b))
  
    def __le__(self, obj):
        return ((self.b) <= (obj.b))
  
    def __ge__(self, obj):
        return ((self.b) >= (obj.b))
  
    def __eq__(self, obj):
        return (self.b == obj.b)
  
    def __repr__(self):
        return str((self.a, self.b))
  
  
# list of objects
gfg = [GFG("geeks", 1),
       GFG("computer", 3),
       GFG("for", 2),
       GFG("geeks", 4),
       GFG("science", 3)]
  
# before sorting
print(gfg)
  
# sorting objects on the basis of value 
# stored at variable b
# after sorting
print(sorted(gfg))


Output:

inside class
[(‘geeks’, 1), (‘computer’, 3), (‘for’, 2), (‘geeks’, 4), (‘science’, 3)]
[(‘geeks’, 1), (‘for’, 2), (‘computer’, 3), (‘science’, 3), (‘geeks’, 4)]



Previous Article
Next Article

Similar Reads

Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python Python throws errors and
4 min read
Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functions that readily come with Python are called built
6 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
How to Write Spark UDF (User Defined Functions) in Python ?
In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our
4 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Python | Scope resolution when a function is called or defined
Python resolves the scope of the parameters of a function in two ways: When the function is definedWhen the function is called When the function is defined Consider this sample program which has a function adder(a, b) which adds an element a to the list b and returns the list b. The default value of b is [1, 8, 11]. Code : C/C++ Code def adder(a, b
3 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all decl
5 min read