Python Program to Sort Objects Without Comparison

  • Python
  • 1 min read

Here is a Python program example to sort objects without native comparison.

Sort Objects in Python Example

The following Python program will print the sorted customer id.

from operator import attrgetter

class Customer:
    def __init__(self, customer_id):
        self.customer_id = customer_id
    def __repr__(self):
        return 'customer({})'.format(self.customer_id)

# Example
customers = [Customer(123), Customer(13), Customer(199)]
print('Unsorted customers', customers)

# Sort it by customer-id
print('Sorted customers', sorted(customers, key=attrgetter('customer_id')))

Output:

Unsorted customers [customer(123), customer(13), customer(199)]
Sorted customers [customer(13), customer(123), customer(199)]

Process finished with exit code 0

See also: