Sorting a list of objects by attribute

Question:

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?

Asked By: gustavlarson

||

Answers:

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.

Answered By: Teemu Kurppa

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

Answered By: Hank Gay
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.