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?
sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.
A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.
You only need to call a. sort() without assigning it to a again. There is a built in function sorted() , which returns a sorted version of the list - a = sorted(a) will do what you want as well.
results.sort(key=lambda r: r.person.birthdate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With