How to Sort a List of Objects by Attribute in Python?

In this tutorial, I will explain how to sort a list of objects by attribute in Python. As a developer working on a project, I came across a scenario where I needed to sort a list of objects by attribute. Then, I explored more about this topic. After researching and testing various methods, I found a few effective methods to accomplish this task.

Sort a List of Objects by Attribute in Python

Let us learn how to sort a list of objects by attribute in Python:

Read How to Print a List Without Brackets in Python?

1. Use a Lambda Function

A lambda function in Python is an anonymous function that can be used to define custom sorting logic. It is flexible and allows you to sort by multiple attributes.

Example:

Sort a list of US states by their name and population.

# List of tuples: (State Name, Population)
states = [
    ("California", 39512223),
    ("Texas", 28995881),
    ("Florida", 21477737),
    ("New York", 19453561),
    ("Pennsylvania", 12801989),
]

# Sort by state name (alphabetically) and then by population (ascending)
sorted_states = sorted(states, key=lambda x: (x[0], x[1]))

print("Sorted by name and population:")
for state in sorted_states:
    print(state)

Output:

Sorted by name and population:
('California', 39512223)
('Florida', 21477737)
('New York', 19453561)
('Pennsylvania', 12801989)
('Texas', 28995881)

You can look at the output in the screenshot below.

Sort a List of Objects by Attribute in Python

The lambda x: (x[0], x[1]) function sorts the list first by the state name (x[0]) and then by population (x[1]). The sorted() function returns a new sorted list.

Check out How to Generate a List of Random Numbers in Python?

2. Use itemgetter

The itemgetter function from the operator module is used to retrieve specific items from an iterable (e.g., lists, tuples). It is efficient and often faster than a lambda function for simple cases.

Example:

Sort a list of US states by their population and then by name.

from operator import itemgetter

# List of tuples: (State Name, Population)
states = [
    ("California", 39512223),
    ("Texas", 28995881),
    ("Florida", 21477737),
    ("New York", 19453561),
    ("Pennsylvania", 12801989),
]

# Sort by population (ascending) and then by state name (alphabetically)
sorted_states = sorted(states, key=itemgetter(1, 0))

print("Sorted by population and name:")
for state in sorted_states:
    print(state)

Output:

Sorted by population and name:
('Pennsylvania', 12801989)
('New York', 19453561)
('Florida', 21477737)
('Texas', 28995881)
('California', 39512223)

You can look at the output in the screenshot below.

How to Sort a List of Objects by Attribute in Python

itemgetter(1, 0) retrieves the population (1) and then the state name (0) for sorting. The sorted() function sorts the list based on the specified keys.

Read How to Slice Lists in Python?

3. Use attrgetter

The attrgetter function from the operator module is used to retrieve attributes from objects. It is useful when working with lists of objects instead of lists of tuples or lists.

Example:

Sort a list of US state objects by their name and population.

from operator import attrgetter

# Define a State class
class State:
    def __init__(self, name, population):
        self.name = name
        self.population = population

    def __repr__(self):
        return f"{self.name} (Population: {self.population})"

# List of State objects
states = [
    State("California", 39512223),
    State("Texas", 28995881),
    State("Florida", 21477737),
    State("New York", 19453561),
    State("Pennsylvania", 12801989),
]

# Sort by state name (alphabetically) and then by population (ascending)
sorted_states = sorted(states, key=attrgetter('name', 'population'))

print("Sorted by name and population:")
for state in sorted_states:
    print(state)

Output:

Sorted by name and population:
California (Population: 39512223)
Florida (Population: 21477737)
New York (Population: 19453561)
Pennsylvania (Population: 12801989)
Texas (Population: 28995881)

You can look at the output in the screenshot below.

Sort a List of Objects by Attribute in Python attrgetter

attrgetter('name', 'population') retrieves the name and population attributes from each State object for sorting. The sorted() function sorts the list of objects based on the specified attributes.

Check out How to Concatenate a List of Strings into a Single String in Python?

Sort by Multiple Attributes

Let us see how to demonstrate sorting a list of employees by their salary in ascending order:

# Define the Employee class and sort employees by salary in one step
class Employee:
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary
    def __repr__(self):
        return f"{self.name} (Age: {self.age}, Salary: ${self.salary})"

# Create a list of Employee objects and sort by salary
employees = sorted([
    Employee("Alice Johnson", 28, 90000),
    Employee("Bob Smith", 34, 75000),
    Employee("Charlie Brown", 22, 60000),
    Employee("David Wilson", 40, 120000),
    Employee("Eva Green", 29, 80000),
], key=lambda x: x.salary)

# Print sorted employees
for employee in employees:
    print(employee)

Output:

Charlie Brown (Age: 22, Salary: $60000)
Bob Smith (Age: 34, Salary: $75000)
Eva Green (Age: 29, Salary: $80000)
Alice Johnson (Age: 28, Salary: $90000)
David Wilson (Age: 40, Salary: $120000)

The Employee class is defined with nameage, and salary attributes. A list of Employee objects is created. The sorted() function sorts the list by the salary attribute using a lambda function (key=lambda x: x.salary). The sorted list is printed, showing employees ordered by salary in ascending order.

Read How to Iterate Through a List Backward in Python?

Conclusion

In this article, I have explained how to sort a list of objects by attribute in Python. I discussed three methods such as using lambda function, using itemgetter, and using attrgetter. I also covered how to sort by multiple attributes.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.