Issue
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
?
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.