Issue with sorting list of objects

Advertisements

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:

[<__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})'

Leave a ReplyCancel reply