>>> arr=[[4,5],[4,6],[6,7],[2,3],[1,1]]
>>> arr.sort(key=lambda x:x[0]) #statement 1
>>> arr
[[1, 1], [2, 3], [4, 5], [4, 6], [6, 7]]
>>> arr.sort(key=lambda x:(x[0],-x[1])) #statement 2
>>> arr
[[1, 1], [2, 3], [4, 6], [4, 5], [6, 7]]
So, I can observe the difference between the execution of statement 1 and statement 2. I am aware that statement 1 sorts the list in ascending order of x[0]. But if we use, statement 2 then how the list is sorted?
lambda x:(x[0],-x[1])
this generates tuples of (the first element, negative of the second element)
When you sort 2-tuples, they are sorted based on
So
arr.sort(key=lambda x:(x[0],-x[1]))
Sorts the list arr
based on:
(that is why [4,6]
is ahead of [4,5]
since -6 < -5
)