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

To sort the list in place:

orig_list.sort(key=lambda x: x.count, reverse=True)

To return a new list, use sorted:

new_list = sorted(orig_list, key=lambda x: x.count, reverse=True)

Explanation:

  • key=lambda x: x.count sorts by count.
  • reverse=True sorts in descending order.

More on sorting by keys.

Leave a Comment