0

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?

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
gustavlarson
  • 417
  • 3
  • 8

2 Answers2

5

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.

S.Lott
  • 373,146
  • 78
  • 498
  • 766
Teemu Kurppa
  • 4,719
  • 2
  • 31
  • 38
2

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

Hank Gay
  • 67,855
  • 33
  • 155
  • 219