How to Sort a List by a property in the object?

 

To sort a list of objects (List<T>) by a specific property in the objects, you can use the sort() or sorted() function in Python. Here's an example demonstrating how to do this:

Suppose you have a list of objects of a class called Person, and you want to sort the list based on the age property of each person.

python
class Person: def __init__(self, name, age): self.name = name self.age = age # Create a list of Person objects people = [ Person("Alice", 25), Person("Bob", 30), Person("Charlie", 22), Person("David", 28) ] # Sort the list of people based on the 'age' property sorted_people = sorted(people, key=lambda person: person.age) # Print the sorted list for person in sorted_people: print(person.name, person.age)

In this example:

  1. We define a Person class with a constructor that initializes the name and age properties.
  2. We create a list named people containing instances of the Person class.
  3. We use the sorted() function to sort the list based on the age property. The key parameter specifies the function that returns the value to be used for sorting (in this case, person.age).
  4. We use a lambda function as the key to extract the age property for each person.
  5. The sorted list is stored in the sorted_people variable.
  6. We loop through the sorted list and print the names and ages of the people.

The output of the example will be:

Charlie 22 Alice 25 David 28 Bob 30

The sorted() function returns a new sorted list without modifying the original list. If you want to sort the list in-place, you can use the sort() method of the list:

python
people.sort(key=lambda person: person.age)

Both the sorted() function and the sort() method allow you to sort a list of objects by a specific property in the objects.

Comments