Sort array of objects using Comparator in python

Problem:- Given an array of  Student objects, sort array using a comparator that sorts them in order of decreasing marks; if  or more students have the same marks, sort those students alphabetically by name.
Input :- Array of Student objects(Student object { Name; Marks;})
amy 90
ckm 90
nikhil 50
shweta 75
ranjan 150

Output
:- Sort based on Marks (Name alphabetically if  marks is same)
ranjan  150
amy    90
ckm   90
shweta  75
nikhil    50

Sample program to sort list of student objects by passing comparator

class Students:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks 
    def comparator(a, b):
        if a.marks != b.marks :
            if a.marks < b.marks :
                return 1
            elif a.marks > b.marks:
                return -1
            else :
                return 0
        else:
            if a.name > b.name :
                return 1
            elif a.name < b.name:
                return -1
            else :
                return 0

print "Enter number of students "
n = int(raw_input())

data = []
for i in range(n):
    print "Enter Name and marks of student %d" %(i+1)
    name, marks = raw_input().split()
    marks = int(marks)
    player = Students(name, marks)
    data.append(player)
    
data = sorted(data, cmp=Students.comparator)
print "\nStudents Name and marks in sorted form "
print "Name \t Marks"
print "----------------"
for i in data:
    print i.name+ " \t "+ str(i.marks)

Sample output:-
>>>
Enter number of students
5
Enter Name and marks of student 1
amy 90
Enter Name and marks of student 2
ckm 90
Enter Name and marks of student 3
nikhil 50
Enter Name and marks of student 4
shweta 75
Enter Name and marks of student 5
ranjan 150

Students Name and marks in sorted form
Name Marks
----------------
ranjan 150
amy 90
ckm 90
shweta 75
nikhil 50

4 Comments

  1. Replies
    1. Sorting objects based on multiple criteria is a useful programming exercise that demonstrates how custom comparison logic can be applied to real-world data. This example sorts student records by marks in descending order and uses alphabetical order by name when students have equal marks. Understanding object-oriented programming, comparison functions, and sorting techniques helps developers organize structured data and solve similar problems efficiently. The example also highlights an older Python syntax, making it useful to understand how sorting approaches have evolved across Python versions.

      Learning Python fundamentals such as classes, objects, functions, and built-in data structures provides a strong foundation for writing maintainable programs. Practising sorting, filtering, and data manipulation with practical examples helps beginners improve their logical thinking and programming confidence. Those interested in strengthening their Python knowledge can explore the Python Online Course in India.

      Delete
    2. Beyond basic programming exercises, Python is widely used for data processing, automation, web development, and AI applications. Developing a deeper understanding of functions, collections, exception handling, and modern Python features can help learners progress toward more advanced projects. For structured learning and practical programming guidance, Python Online Training in India is another resource to consider.

      Delete
Previous Post Next Post