HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howsortattributetheobjectslistbased

Problem

I have a list of Python objects that I want to sort by a specific attribute of each object:

[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]


How do I sort the list by .count in descending order?

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#403421, score: 2044

Revisions (0)

No revisions yet.