0

I know that the sorted method here sorts my list in ascending order but how does this lambda function changes the functionality of my code?

list = [ (1,4), (0,8), (5,6), (7,10)]

list_sorted = sorted(list, key = lambda list: list[1], reverse = False)

print("Sorted:", list_sorted)

3 Answers3

0

The key parameter of the sorted function modifies the sorting. Instead of comparing based on the values, it'll compare based off the value returned by the key function. In this case, key returns the second element of the tuple, so the list will be sorted based off the second element of the tuple, and not the first like tuples normally are.

See the official docs for more info.

(to be pedantic tuples aren't sorted by the first element, they're sorted lexicographically starting from the first element)

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

Each element of the iterable is passed to the sorting function, then you're extracting and comparing on the second elements of each item as the key

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Short remark: Please don't call your list list. It overrides the python list method an can lead to some confusing error messages

You can apply the lambda function by using map to see what it does:

In [9]: your_list = [ (1,4), (0,8), (5,6), (7,10) ]                                                                                                                                                        

In [11]: list(map(lambda x: x[1], your_list))                                                                                                                                                              
Out[11]: [4, 8, 6, 10]

So for each tuple inside your list it takes the second elements (counting starts at 0). When you call sorted it then sorts this elements reorders the tuples accordingly.

In your cases the output of the lambda is already sorted correctly, so the sorted functions does not need to reorder anything

In [13]: sorted(your_list, key = lambda x: x[1], reverse = False)                                                                                                                                          
Out[13]: [(1, 4), (5, 6), (0, 8), (7, 10)]

If you had initialized your_list in a different order you would still get the same result

In [14]: your_list = [ (0,8), (1,4), (7,10), (5,6) ]                                                                                                                                                       

In [15]: sorted(your_list, key = lambda x: x[1], reverse = False)                                                                                                                                          
Out[15]: [(1, 4), (5, 6), (0, 8), (7, 10)]
maow
  • 2,712
  • 1
  • 11
  • 25