"Python: Sort List of Objects by Attribute"

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 Collection Data Types | Lists, Tuples, Sets & Dictionaries Explained
Python Collection Data Types | Lists, Tuples, Sets & Dictionaries Explained

```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:

All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)

```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.

How to Sort a List in Python?
How to Sort a List in Python?
Python list operations cheat sheet
Python list operations cheat sheet
Python Lists infographic for beginners
Python Lists infographic for beginners
Python List Methods Everyone Must Know
Python List Methods Everyone Must Know
Python Syntax Data Collections
Python Syntax Data Collections
PYTHON BASICS
PYTHON BASICS
Python List index() Method Explained with Examples
Python List index() Method Explained with Examples
two tables with the words list vs set and other things that are in each table
two tables with the words list vs set and other things that are in each table
Python Sort Dictionary by Key and Value with Example
Python Sort Dictionary by Key and Value with Example
Python list indexing tutorial guide
Python list indexing tutorial guide
Python array sorting guide #python #programming #tutorial
Python array sorting guide #python #programming #tutorial
Python list sorting cheat sheet
Python list sorting cheat sheet
Python list methods every developer should know.
Python list methods every developer should know.
Python lists cheat-sheet infographic
Python lists cheat-sheet infographic
Python List functions
Python List functions
Python Unit 5 Cheat Sheet 🐍 | File Handling & OOP Basics (AKTU)
Python Unit 5 Cheat Sheet 🐍 | File Handling & OOP Basics (AKTU)
Python list methods reference chart
Python list methods reference chart
an info sheet with the words important method in python, set list and keywords
an info sheet with the words important method in python, set list and keywords
Python list exercises guide
Python list exercises guide
Python list removal methods guide
Python list removal methods guide
python list
python list
Class vs Object in Python – Simple Explanation with Example
Class vs Object in Python – Simple Explanation with Example
Data Structures
Data Structures
Ultimate Python Cheat Sheet for Beginner
Ultimate Python Cheat Sheet for Beginner