Sort python list by function

Question:

I have a function that takes an object as an argument and gives me a number. I wish to use this number as the key to sort my list.

If I were to iterate over the list I would do something like:

sorted_list = []
for object in my_list_of_objects:
    i = my_number_giving_function(object)
    sorted_list.insert(i, object)

How can I user sorted to get the same result, and is it advisable? This is what I came up with but I don’t know what to put in the ‘???’

sorted_list = sorted(my_list_of_objects, key=my_number_giving_function(???))
Asked By: vascop

||

Answers:

sort(my_list_of_objects, key=my_number_giving_function)

same for sorted, see the Python Sorting HOWTO

Answered By: msw
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.