[python] Sort a list of Class Instances Python

I have a list of class instances -

x = [<iteminstance1>,...]

among other attributes the class has score attribute. How can I sort the items in ascending order based on this parameter?

EDIT: The list in python has something called sort. Could I use this here? How do I direct this function to use my score attribute?

This question is related to python sorting

The answer is


In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()