Sort a list of Class Instances Python

Question:

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?

Asked By: Inception

||

Answers:

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))
Answered By: Ned Batchelder

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()
Answered By: kindall
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.