How to Sort in Python with the Lambda Function

What is the output of this puzzle?


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

# lexicographical sorting (ascending)
pairs.sort(key=lambda pair: pair[1])


The high Elo indicates that only experienced Python coders can solve this puzzle. There are two barriers to overcome.

First, the lambda function seems to be an abstract concept. Yet, it is only old wine in a new bottle. A lambda function is nothing but an anonymous function with a special syntax. The variable name(s) between the lambda keyword and the colon (:) define the function arguments. The body after the colon uses the arguments to define the return value of the function. In the puzzle, we use the lambda function as a key for the sorting function. The key defines that the list should be sorted after the second value of the tuple which is a string.

Second, we are not sorting by ascending integers, i.e., 1,2,3,4, but by ascending strings according to their position in the alphabet, i.e., ‘four’, ‘one’, ‘three’, ‘two’. So the second tuple element from the first list element is ‘four’.

Are you a master coder?
Test your skills now!

Related Video




Leave a Comment