Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with sorting list of objects

I’m having trouble sorting a list of objects in Python. I have a list of Person objects, and I want to sort them based on their age. However, the sorting doesn’t seem to be working as expected. Here’s my code:

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

people = [
    Person("Alice", 30),
    Person("Bob", 25),
    Person("Charlie", 40),
    Person("David", 22)
]

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

I expected the output to be a list of Person objects sorted by their age, like this:

[Person("David", 22), Person("Bob", 25), Person("Alice", 30), Person("Charlie", 40)]

However, the actual output I’m getting is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[<__main__.Person object at 0x...>, <__main__.Person object at 0x...>, ...]

It seems like the sorting is not working as intended. What am I doing wrong? How can I fix this sorting issue?

>Solution :

Add a __repr__ implementation to your class to get nice default string representations:

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

    def __repr__(self):
        return f'Person({repr(self.name)}, {self.age})'

As Kelly Bundy points out, you can also use the !r shorthand in the f-string literal to call repr() on the member items:

class Person:
    # ...
    def __repr__(self):
        return f'Person({self.name!r}, {self.age!r})'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading