How to sort a list of objects based on an attribute of the objects?

Nick Sergeant picture Nick Sergeant · Dec 31, 2008 · Viewed 588.1k times · Source

I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:

>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,
 <Tag: aes>, <Tag: ajax> ...]

Each object has a count:

>>> ut[1].count
1L

I need to sort the list by number of counts descending.

I've seen several methods for this, but I'm looking for best practice in Python.

Answer

Triptych picture Triptych · Dec 31, 2008
# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

More on sorting by keys.