-3

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

3

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})'
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

The list is probably sorted exactly right!
You are seeing the default representation for a python object.
If you want to see a nicer looking output when printing, look into implementing one of the following "dunder" methods, __str__() or __repr__().
A good Tutorial here.

It might end up looking something like this:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return f'Name: {self.name} Age: {self.age}'
Paolo Sini
  • 176
  • 10