BSG
BSG

Reputation: 1452

Most efficient way to sort list of objects by attribute?

I have a (small) list of objects that i'd like to sort by an attribute, descending.

such as:

obj1.age = 1
obj2.age = 2
obj3.age = 3

list = [obj3,obj2,obj1]

Upvotes: 1

Views: 169

Answers (2)

user2555451
user2555451

Reputation:

Since your list is small, there isn't a need to import operator.attrgetter. Using sorted with a lambda function will run just as well:

sorted(lst, key=lambda x: x.age, reverse=True)

In the above code, lst is the list. I changed the name because it is bad practice to name a variable list since doing so overshadows the built-in.

Also, this solution is not an in-place one. Meaning, you can assign it to a variable:

new_lst = sorted(lst, key=lambda x: x.age, reverse=True)

Upvotes: 5

Jon Clements
Jon Clements

Reputation: 142146

Use operator.attrgetter and .sort:

from operator import attrgetter
your_list.sort(key=attrgetter('age'), reverse=True)

Upvotes: 8

Related Questions