0

I'm reading the python tutorial document and can't understand the result of one example in lambda function. the example is:

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] 
pairs.sort(key=lambda pair: pair[1]) 
pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

In my understanding, pairs.sort(key=lambda pair: pair[1]) means sort the pairs using the result of lambda function. The argument of lambda function is pair, and the result is pair[1], which means the second value of pair list? Then how would this key get the sort of [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]? Could anyone nicely explain it for me?

alex
  • 10,900
  • 15
  • 70
  • 100
Panky
  • 1
  • All it means is that the key for sorting is the second element of each tuple in the lists. So it sorts on the words such as 'four'. It you used pair[0] it would sort on the numbers such as 4 and get a different sorted order - you can try this. – user19077881 Dec 08 '22 at 13:13
  • A better understanding of the lamda would help here, Recommend you to read this answer - https://stackoverflow.com/a/42966511/9117239 – Jai dewani Dec 08 '22 at 13:13

1 Answers1

0

lambda is called an anonymous function. The argument is passed before the ":". The expression which returns some value is after the colons. In this case, this is pair[1] which points to the second element of an iterable. So the list will be sorted by the second element of the tuples. lambda pair: pair[1]