Nikunj Parmar
Nikunj Parmar

Reputation: 29

How does this lambda function work in python 3?

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

print(pairs)

Ans:

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

How does the pair argument work here?

Upvotes: 0

Views: 140

Answers (1)

blue note
blue note

Reputation: 29081

When you want to sort a collection, the key parameter is a function that is used to extract from each element the value by which you want to sort. The function takes the argument, produces a value, and uses this value to sort the list

In your case, lambda pair: pair[1], is just an anonymous function that takes your (x, y) pairs of values and returns only the y. Since those values are strings in your case, your list is sorted in alphabetical order of the second value of each tuple.

Upvotes: 2

Related Questions