Second python program: classes, sorting

Peter Otten __peter__ at
Sun Aug 10 21:50:48 CEST 2008

WP wrote:

> I solved it, I rewrote __cmp__ to:
> def __cmp__(self, other):
>     if self.score == other.score:
>        return cmp(,
>     else:
>        return cmp(other.score, self.score)

You can simplify that to

def __cmp__(self, other):
    return cmp(other.score, self.score) or cmp(,

Alternatively you can define a key function

def descending_score(s):
    return -s.score,

and then use it:


Because list.sort() is stable sorting twice will also work:

scores.sort(key=lambda s:
scores.sort(key=lambda s: s.score, reverse=True)


More information about the Python-list mailing list