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.
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:
Sort a list of objects based on an attribute of the objects in Python
my_list.sort(key=lambda x: x.my_attribute)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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:
Sort a list of objects based on an attribute of the objects in descending order in Python
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.
Sort a list of objects based on an attribute of the objects in Python using the sorted function
sorted_list = sorted(my_list, key=lambda x: x.my_attribute)