Sort a 2D list first by column 1 and then by column 2

I am trying to find a good way to sort a 2d list, first by 1st value, and then by 2nd value.

I think the example would be best if I have a list

[[1,4], [2,7], [10,1], [1,2], [10,6] [2,1]] 

I want this to be sorted as follows

 [[1,2], [1,4], [2,1], [2,7], [10,1], [10,6]] 
+7
python sorting list
source share
1 answer
 l=[[1,4], [2,7], [10,1], [1,2], [10,6], [2,1]] print sorted(l,key=lambda x: (x[0],x[1])) # use lambda to sort by "x[0]"-> first element of the sublists or x[1] -> second element, if its a tie [[1, 2], [1, 4], [2, 1], [2, 7], [10, 1], [10, 6]] 

Or just sorted(l) of l.sort() , since your items are sorted naturally.

A better example would be sorting by the second value only:

 print sorted(l,key=lambda x: (x[1])) [[10, 1], [2, 1], [1, 2], [1, 4], [10, 6], [2, 7]] 
+13
source share

All Articles