0

I created class named Student() with attributes name and surname. In that class I created class variable -> all_students = []

When creating an object, it is being added to that class variable = all_students.

How to sort that list of objects by the lenght of the attribute name from longest to shortest?

import operator
class Student:

    all_students = []
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname
        Student.all_students.append(self)

s_1 = Student("Jacobbbb", "anything")

s_2 = Student("Mat", "anything1")

s_3 = Student("Marcooooooo", "sss")


new_list = sorted(Student.all_students, key=operator.attrgetter(len('name')))

for student in new_list:
    print(student.name)

I tried with operator, but I can't do that in this way. Will be gratefull for help.

3 Answers 3

6

You're almost there. You just need to change your key a bit to use a lambda:

sorted(Student.all_students, key=lambda x: -len(x.name))

This'll sort your student list in descending order of name length (notice the -len(...).

If you wanted to use attrgetter, you'd need to change your key to key=lambda x: -len(operator.attrgetter('name')(x)). But at that point, it becomes simpler to just use x.name.


Here's a demonstration. I've added a __repr__ method so it becomes clearer.

In [320]: def __repr__(self): return 'Student(%s %s)' %(self.name, self.surname)

In [321]: Student.__repr__ = __repr__

In [322]: sorted(Student.all_students, key=lambda x: -len(x.name))
Out[322]: [Student(Marcooooooo sss), Student(Jacobbbb anything), Student(Mat anything1)]
Sign up to request clarification or add additional context in comments.

Comments

2

I haven't enough reputation to comment yet:

COLDSPEED's solution is good, but more pythonic still to use a key function (not lambda), and use the reverse arg

def name_length(student):
    return len(student.name)


sorted(Student.all_students, key=name_length, reverse=True)

Comments

0

You can't do it with attrgetter. Use a lambda:

sorted(Student.all_students, key=lambda s: len(s.name))

2 Comments

OP wants it sorted in reverse, so you'd need -len(s.name).
... or reverse=True.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.