# Issue

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

# Solution

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

- The first element
- 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:

- the first element
- 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`

)

Answered By - rdas Answer Checked By - Gilberto Lyons (PHPFixing Admin)

## 0 Comments:

## Post a Comment

Note: Only a member of this blog may post a comment.