Skip to content
Advertisement

Python – Sort a list of lists but only keep last item in each sublist

I have a list of items that I need to sort according to a given score I give it. The code looks something like this:

original_list = [item_1, item_2, item_3]
# ... Here I score the list in a separate function to get a score for each item ...
scored_list = [[35, item_1], [45, item_2], [1, item_3]]
scored_list.sort()
sorted_list = [item[1] for item in scored_list]

So I have a list of items, score each item, sort the list according to the score, and then remove the score variable to keep only the items.

Is this the most efficient way of doing this kind of operation, or are there simpler ways to obtain the same result?

Advertisement

Answer

Efficiency-wise I doubt you can do better. If you are concerned with the number of lines, you can move the sort to inside the comprehension:

scored_list = [[35, item_1], [45, item_2], [1, item_3]]
sorted_list = [item[1] for item in sorted(scored_list)]

But in terms of speed you’ll likely not notice a difference. In fact this may be a bit slower than your approach because in-place sort() might be a bit faster as it does not need to make a copy but depending on your data that is negligible.

So I’d say your approach is perfectly fine. If you want to make it more concise, you can use sorted().

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement