This article shows how to sort in Python using the key argument that takes a function as argument. You can use the lambda function to create the function on the fly as shown in the following example:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] # lexicographical sorting (ascending) pairs.sort(key=lambda pair: pair) print(pairs)
This is one of the most popular Python puzzles on the Finxter app. Before I explain the output, try to come up with your own guess:
What is the output of this puzzle?
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 (find a thorough introduction of lambda functions in this Finxter blog article).
In short: 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.
You can go over the following Instagram tutorial (swipe right) to learn more about this Python feature:
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!
Solution to the Python Puzzle
Where to Go From Here?
The lambda function is one element every Python master coder understands. Do you? If you struggle with basic Python features like this, download my Python cheat sheets. Print them. And post them to your office wall!