How Do I Sort A List Of Objects Based On An Attribute Of The Objects?

In this post, we will learn How to Sort a list of objects based on an attribute of the objects which we can perform using the sort built in function even we can do the same thing using the sorted function to and here we will discuss both the examples and execution with the help of some examples.


Sort A List Of Objects

As sorting is nothing but arranging the objects in a particular order and it could be ascending or descending order and here we will give an example of code of both.

Even for sorting the objects in a list we use the sort() method and sorted in built function so here we have given an example to implement the same where we simply sorted the list which has a person object and there each object has attributes such as name, age, and height.

class Person:
    def __init__( self, name, age, height): = name
        self.age = age
        self.height = height

person1 = Person(" John", 25, 180)
person2 = Person(" Jane", 30, 165)
person3 = Person(" Bob", 20, 175)

people = [person1, person2, person3]

To sort this list by the age attribute, you can use the sort method and a lambda function that returns the age attribute of each object:

people.sort( key=lambda x: x.age)

Here we have used the sort() function for getting the list of objects sorted and as we have another alternative for the same which is the sorted() function here we have given the example for use.

sorted_people = sorted( people, key=lambda x: x.age)

And even after sorting, the objects like people and the sorted persons will both store the same objects in ascending order of age. You can also sort in descending order by adding the reverse == true argument.

people.sort( key=lambda x: x.age, reverse=True)
sorted_people = sorted( people, key=lambda x: x.age, reverse=True)

And here the above code will help in sorting the same objects in descending order of the field age as it is required.



To learn more about How to sort a list of objects based on an attribute of the objects visit: How do I sort a list of objects based on an attribute of the objects by Stack over flow

To learn more about python solutions to different python problems and tutorials for the concepts we need to know to work on python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

To learn more about different other programming languages like java, MySQL, MongoDB, and other language solutions visit: beta python programming languages Solutions.

Leave a Comment

%d bloggers like this: