Explain Codes LogoExplain Codes Logo

How do I sort a list of objects based on an attribute of the objects?

python
sorting
key-function
lambda-functions
Anton ShumikhinbyAnton Shumikhin·Aug 21, 2024
TLDR

Easily sort objects by an attribute with sorted() and a key function:

sorted_list = sorted(obj_list, key=lambda x: x.attribute)

In case you're going down a hill, switch to descending order with reverse=True:

sorted_list = sorted(obj_list, key=lambda x: x.attribute, reverse=True)

Exploring the object sorting cosmos

attrgetter for speed demons

For those in need for speed, using operator.attrgetter() leaves lambdas eating dust:

from operator import attrgetter # Vroom... Vroom... sorted_list = sorted(obj_list, key=attrgetter('attribute'))

Sorting: Now in 3D! (Using custom class methods)

Design your own abstract art of sorting by defining __eq__ and __lt__ inside your class:

class MyObject: # Constructor for the art piece... eh I mean object. def __init__(self, attribute): self.attribute = attribute # Picasso would be proud of this abstract compareTo 𝓐𝓻𝓽. def __lt__(self, other): return self.attribute < other.attribute

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:

# "Lambda, Lambda, give me the funk!" *funky guitar riff* sorted_list = sorted(obj_list, key=lambda obj: obj.attribute)

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:

# I'm like a rubik's cube. The more you play with me, the harder I get. sorted_by_date = sorted(obj_list, key=attrgetter('date')) # Time travel mode... Engage! sorted_by_name = sorted(obj_list, key=attrgetter('name')) # Scrabble mode... Engage!

Ninja-style inlining

For swift one-off sorts, inline lambda functions are your sneaky friends:

# Code like a ninja, sort like a boss! sorted_list = sorted(obj_list, key=lambda x: getattr(x, 'attribute', default_value))

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:

# I see null, I see defaults. Perfectly balanced, as all things should be. sorted_list = sorted(obj_list, key=lambda x: getattr(x, 'attribute', 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:

# Two-step sorting. Like line dancing, but more Pythonic! obj_list.sort(key=attrgetter('secondary_attribute')) # Step 1: Get the groove on! obj_list.sort(key=attrgetter('primary_attribute')) # Step 2: Switch it up!