How to sort a list of objects based on an attribute of the objects?
You can use the sort
method of a list and pass in a key
argument, which is a function that takes an object and returns the value on which you want to sort the list. For example, if you have a list of objects my_list
and each object has an attribute my_attribute
, you can sort the list based on that attribute like this:
my_list.sort(key=lambda x: x.my_attribute)
Watch a video course
Python - The Practical Guide
This will sort the list in ascending order based on the value of my_attribute
. To sort in descending order, you can pass in the reverse=True
argument:
my_list.sort(key=lambda x: x.my_attribute, reverse=True)
Alternatively, you can use the sorted()
function in python that takes in the list and a key function and returns a sorted list.
sorted_list = sorted(my_list, key=lambda x: x.my_attribute)