48

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

85
results.sort(key=lambda r: r.person.birthdate)
Sign up to request clarification or add additional context in comments.

6 Comments

Actually I don't think you want that reverse=True.
Yeah, I already removed it; had a slight brainfart about "oldest".
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.
I'll raise it as a new question
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.
|
17

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 Comments

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.
@J.F. Sebastian: agreed, I just quoted the wiki:) I'll edit the answer

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.