45

I have a Python list called results. Each result in the results list has a person object, and each person object has a birthdate (result.person.birthdate). The birthdate is a datetime object.

I would like to order the list by birthdate with the oldest first. What is the most Pythonic way to do this?

2 Answers 2

81
results.sort(key=lambda r: r.person.birthdate)
6
  • 1
    Actually I don't think you want that reverse=True.
    – rlibby
    Feb 20, 2011 at 7:31
  • 2
    Yeah, I already removed it; had a slight brainfart about "oldest".
    – Amber
    Feb 20, 2011 at 7:32
  • Just noticed some of the objects have person object set to None. I still want these results in the list. How can I do this while still sorting the others? Thanks.
    – shane
    Feb 20, 2011 at 7:48
  • I'll raise it as a new question
    – shane
    Feb 20, 2011 at 8:06
  • 8
    Watch out: list.sort sorts in-place instead of returning the sorted list. Use sorted(results, key=...) if you don't want to mutate the original list. Oct 20, 2014 at 13:12
16

Totally agree with Amber, but there is another way of sorting by attribute (from the wiki: https://wiki.python.org/moin/HowTo/Sorting):

from operator import attrgetter
sorted_list = sorted(results, key=attrgetter('person.birthdate'))

This method can actually be even faster than sorting with lambda

2
  • 3
    attrgetter() is convenient if 'person.birdate' is passed as a variable. Otherwise the lambda` is more flexible (e.g., what if person is None sometimes) and the time difference should be negligible in most cases.
    – jfs
    Oct 12, 2014 at 16:57
  • @J.F. Sebastian: agreed, I just quoted the wiki:) I'll edit the answer
    – yentsun
    Oct 20, 2014 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.