[SOLVED] How to sort a list of list with the first value, if the both are equal check the second and so on

Issue

This Content is from Stack Overflow. Question asked by jdsouza

If you are given a list of list (heterogenous). How do I sort it based on first value and if first value are equal then sort using the second value for those items and even if second values are equal then sort using the third value and so on.

I know how to sort using a particular index of the inner list

Let a list be:

a = [[2,2,3],[2,2,4],[2,1,1],[2,2,5],[1,2,6],[2,2,2]]  

I want:

a=[[1,2,3],[2,1,1],[2,2,2],[2,2,3],[2,2,4],[2,2,5]]

using,

a = sorted(a, key = lambda x:x[0])  

will sort it using the first value, but if the first value is equal then it will add the values according to values which come first.

How do I go about with this? If on getting the first value equal, I wanted to sort using the last value in the inner list how would I do that?



Solution

Literally it sorts with using sorted():

a = [[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]] 
print(sorted(a, key=lambda a: (a[0], a[-1])))
# output - [[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]


This Question was asked in StackOverflow by jdsouza and Answered by rockzxm It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?