Sorting a List of Objects by Attribute in Python
In Python, sorting a list of objects by a specific attribute is a common task when you want to organize data based on a particular criterion. This can be achieved using the built-in `sorted()` function or the list's `sort()` method, along with a lambda function or the `attrgetter` function from the `operator` module. Let's explore these methods with practical examples.
Using the `sorted()` Function with a Lambda Function
The `sorted()` function returns a new sorted list from the elements of any sequence. It doesn't modify the original list. To sort by an attribute, you can use a lambda function as the key parameter. Here's an example using a list of custom objects:
```python class Person: def __init__(self, name, age): self.name = name self.age = age people = [ Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35), ] sorted_people = sorted(people, key=lambda p: p.age) ```
Using the `sort()` Method with a Lambda Function
If you want to sort the list in-place (without creating a new list), you can use the list's `sort()` method. It also accepts a key function, which can be a lambda function:

```python people.sort(key=lambda p: p.age) ```
Using the `attrgetter` Function
The `attrgetter` function from the `operator` module can also be used as a key function. It's a more concise way to sort by an attribute, especially when you're dealing with complex objects:
```python from operator import attrgetter sorted_people = sorted(people, key=attrgetter('age')) ```
Sorting in Descending Order
To sort in descending order, you can use the `reverse` parameter or the `-` operator with the key function:
```python # Using reverse parameter sorted_people = sorted(people, key=lambda p: p.age, reverse=True) # Using - operator with key function sorted_people = sorted(people, key=lambda p: -p.age) ```
Sorting by Multiple Attributes
You can also sort by multiple attributes by providing a tuple of keys to the key parameter:

```python sorted_people = sorted(people, key=lambda p: (p.age, p.name)) ```
Sorting with Custom Comparison Function
If you need more complex sorting logic, you can provide a custom comparison function as the key parameter:
```python def older_than_30(p): return p.age > 30 sorted_people = sorted(people, key=older_than_30) ```
Summary
Sorting a list of objects by an attribute in Python is straightforward using the `sorted()` function or the list's `sort()` method with a lambda function or the `attrgetter` function. You can also sort in descending order, by multiple attributes, or with a custom comparison function. Understanding these methods will help you efficiently organize data based on specific criteria in your Python applications.























