tags:

views:

117

answers:

2

I am trying to sort a list of objects in python, however this code will not work:

import datetime

class Day:
    def __init__(self, date, text):
        self.date = date
        self.text = text

    def __cmp__(self, other):
        return cmp(self.date, other.date)

mylist = [Day(datetime.date(2009, 01, 02), "Jan 2"), Day(datetime.date(2009, 01, 01), "Jan 1")]
print mylist
print mylist.sort()

The output of this is:

[<__main__.Day instance at 0x519e0>, <__main__.Day instance at 0x51a08>]
None

Could somebody show me a good way solve this? Why is the sort() function returning None?

+5  A: 

mylist.sort() returns nothing, it sorts the list in place. Change it to

mylist.sort()
print mylist

to see the correct result.

See http://docs.python.org/library/stdtypes.html#mutable-sequence-types note 7.

The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

tequilatango
-1: no quote from the documentation.
S.Lott
Ah, silly me. Thanks a lot.
gustavlarson
+2  A: 

See sorted for a function that will return a sorted copy of any iterable.

Hank Gay
IOW, `print sorted(mylist)`
Ryan Ginstrom
'sorted' doesn't modify the original list. Sometimes you want to modify the original list, sometimes you don't.
Rory
I know. That's why it returns a "sorted copy", not "a reference to the sorted list".
Hank Gay