Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does arr.sort(key=lambda x: (x[0],-x[1])) mean?

>>> 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?

like image 685
Subhadip Avatar asked Sep 20 '25 17:09

Subhadip


1 Answers

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

  1. The first element
  2. If the first elements are equal, then the second element

So

arr.sort(key=lambda x:(x[0],-x[1]))

Sorts the list arr based on:

  1. the first element
  2. if the first elements are equal, then based on the negative of the second element.

(that is why [4,6] is ahead of [4,5] since -6 < -5)

like image 135
rdas Avatar answered Sep 22 '25 09:09

rdas