I'm new to python and I'm having trouble trying to sort a list correctly. I have a map of strings->Word objects. A word object contains a list of all the places in a file where the word occurs. So in the Word class I have this method:

def _cmp_(self,other):
        return other.num_occurences()-self.num_occurences()

Then elsewhere I have this code:

values = map.values()#list of Word objects
values.sort()#need to sort based on length of occurences

But it isn't sorting based on the cmp method. I put that print statement in the cmp method so that if values.sort() called the cmp method it would print 'here' but nothing prints.

9 Years
Discussion Span
Last Post by Gribouillis

That's because the current implementation uses the method __lt__ to sort (self < other). So you should implement this method.


so sort uses the __lt__ method? What does the __cmp__ method get used for then?


I don't really know if __cmp__ is still used for something, because I don't use it, but in the old versions of python, there was only the __cmp__ method, and it was used for sorting. The methods __le__, __lt__, __ge__, __gt__ etc appeared later and were called the 'rich' comparison operators. So they belong to 2 different layers in the evolution of python. May be __cmp__ was kept because of existing code.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.