Last modified: Nov 26, 2024 By Alexander Williams

Sort List of Objects by Attribute in Python

Sorting a list of objects by an attribute is a common task in Python. This article covers various techniques to sort efficiently and flexibly.

Whether you are working with simple or complex objects, Python provides several methods to help you sort lists with ease.

Using the sorted() Function

The sorted() function is a powerful way to sort lists. You can provide a key parameter to define the sorting logic.


# Define a class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create a list of objects
people = [
    Person("Alice", 30),
    Person("Bob", 25),
    Person("Charlie", 35)
]

# Sort by age
sorted_people = sorted(people, key=lambda person: person.age)

# Print sorted names
print([person.name for person in sorted_people])


['Bob', 'Alice', 'Charlie']

Using lambda, we specify the attribute to sort by, such as person.age. The original list remains unchanged.

Using the sort() Method

The sort() method is similar to sorted() but modifies the original list in place. It’s useful when you don’t need to keep the original list.


# Sort the original list by name
people.sort(key=lambda person: person.name)

# Print sorted names
print([person.name for person in people])


['Alice', 'Bob', 'Charlie']

Since sort() works in place, it doesn’t return a new list, saving memory for large datasets.

Sorting in Reverse Order

You can sort in descending order by using the reverse parameter in both sorted() and sort().


# Sort by age in descending order
sorted_people = sorted(people, key=lambda person: person.age, reverse=True)

# Print sorted names
print([person.name for person in sorted_people])


['Charlie', 'Alice', 'Bob']

Setting reverse=True reverses the sorting order, making it ideal for ranking scenarios.

Using attrgetter for Readability

The attrgetter() function from the operator module is an alternative to lambda for improved readability.


from operator import attrgetter

# Sort by age using attrgetter
sorted_people = sorted(people, key=attrgetter('age'))

# Print sorted names
print([person.name for person in sorted_people])


['Bob', 'Alice', 'Charlie']

attrgetter() is particularly useful when dealing with deeply nested attributes or when clarity is a priority.

Sorting Multiple Attributes

Sometimes, you need to sort by more than one attribute. Use a tuple as the key to achieve this.


# Sort by age, then by name
sorted_people = sorted(people, key=lambda person: (person.age, person.name))

# Print sorted names
print([person.name for person in sorted_people])


['Bob', 'Alice', 'Charlie']

This approach is helpful when you want a secondary sorting criterion for tie-breaking.

Sorting Complex Objects

If the attribute is nested or computed, extract it in the key function. Here's an example:


# Add a computed property
class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

    def name_length(self):
        return len(self.name)

people = [
    Person("Alice", 30, "NY"),
    Person("Bob", 25, "LA"),
    Person("Charlie", 35, "SF")
]

# Sort by name length
sorted_people = sorted(people, key=lambda person: person.name_length())

# Print sorted names
print([person.name for person in sorted_people])


['Bob', 'Alice', 'Charlie']

This method provides flexibility for sorting based on dynamic attributes.

Related Topics

Learn more about list operations like removing elements with the pop method or accessing list indexes.

Conclusion

Sorting a list of objects by attribute is essential for organizing and analyzing data in Python. With methods like sorted(), sort(), and attrgetter(), Python offers robust solutions.

Practice these techniques to handle various sorting scenarios efficiently!