Can .sort() method be used to sort spesific objects by overriding it?

I have an object containing an integer number and string. I created these objects and add all of them to a list but I can’t sort them according to the numbers they contain . How can i sort the objects ?

1 Like

Welcome to the discuss community!

You can only sort objects with a named attribute.
So we have a class and a list containing the objects:

class Delivery:
  def __init__(self, name, houseNum):
    self.name = name
    self.houseNum = houseNum
  def __repr__(self):
     return repr((self.name, self.grade, self.age))

orders = [Delivery("Joe", 5),Delivery("Alfie", 4),Delivery("Charlie", 6),Delivery("Matt", 3)]

Then we can use .sort() or sorted(), by setting the parameter, key to a lambda function with a parameter that python will set to the current object (I assume order[i] but it depends on the sorting algorithm it uses) when it loops through the list, which will then return the houseNum value for python, which will sort it using our returned value:

orders_sorted = sorted(orders, key=lambda order : order.houseNum)

I hope this helps :grinning:


If something isn’t clear then just reply and I’ll try to clarify it.
I’d recommend taking a look at python’s howto page about sorting

2 Likes