sort list of objects by return of object method

list, python, python-2.7, sorting

Solution

Just use the `key` argument to the `sorted()` function or `list.sort()` method:

sorted_list = sorted(list_of_objects, key=function_that_calculates)

The `function_that_calculates` is called for each entry in `list_of_objects` and its result informs the sort.

If you meant that each object has a method, you can use a `lambda` or the `operator.methodcaller()` object to call the method on each element:

sorted_list = sorted(list_of_objects, key=lambda obj: obj.method_name())

or

from operator import methodcaller

sorted_list = sorted(list_of_objects, key=methodcaller('method_name'))

Note that in Python, there is no such thing as a private attribute; your sorting function can still just access it. The leading underscore is just a convention. As such, sorting by a specific attribute can be done with either a `lambda` again, or using the `operator.attrgetter()` object:

sorted_list = sorted(list_of_objects, key=lambda obj: obj._variable_name)

or

from operator import attrgetter

sorted_list = sorted(list_of_objects, key=attrgetter('_variable_name'))

Problem

I've got a list of objects, that have a function which does some calculations on several member variables and returns a value. I want to sort the list according to this return value. I've found how to sort a list of objects by member variables but I want to keep them private (`_variable_name`). Is there an easy way to accomplish this similar to the method of sorting the list directly by the members of the objects?

Original source