How do I sort a list of objects based on an attribute of the objects?
Easily sort objects by an attribute with sorted() and a key function:
In case you're going down a hill, switch to descending order with reverse=True:
Exploring the object sorting cosmos
attrgetter for speed demons
For those in need for speed, using operator.attrgetter() leaves lambdas eating dust:
Sorting: Now in 3D! (Using custom class methods)
Design your own abstract art of sorting by defining __eq__ and __lt__ inside your class:
Now, sorted(list_of_objects) gracefully waltzes around with these class-defined comparison methods.
Life without attrgetter
Dancing with lambda
Can't take operator out for a spin? Go to prom with good ol' lambda:
Performance theater: starring timsort & attrgetter
While timsort enjoys its fame with key=, the performance can vary with the complexity of objects. attrgetter can save the day with a significant speed boost for heavier objects.
Exploring key=: the Swiss Army knife of sorting
Attribute-swapping made easy
The key= lever lets you shift gears effortlessly, switching attributes in no time:
Ninja-style inlining
For swift one-off sorts, inline lambda functions are your sneaky friends:
Stranded without import?
When import sticks its tongue out, the trusty lambda twist comes to the rescue:
Sorting’s secret stories
Handling Chameleons with grace
Elegantly sort objects with nullable attributes by offering a peaceful olive branch with default value:
Stability you can count on
Python's sort is rock solid stable. When two elements compare equal, their original party line is maintained. A gem for multi-level sorting:
Was this article helpful?