Pablo
Pablo

Reputation: 5087

pythonic way to sort a list of lists by the last item of the inner list

I have a list like this

[[x,y,1],[w,u,4],[m,n,3] ... [p,q,5]]

I need to sort the outer list by the third (last) element of the inner list, the desired result would be:

[[x,y,1],[m,n,3],[w,u,4] ... [p,q,5]]

What's the best way to achieve this?

Upvotes: 3

Views: 147

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602115

my_list.sort(key=lambda x: x[-1])

or

my_list.sort(key=operator.itemgetter(-1))

The second option is slightly faster.

Upvotes: 5

Related Questions