How to Sort in Python with the Lambda Function as Key Argument?

Challenge: This article shows how to sort a Python list using the key argument that takes a function object as an argument.

Quick Solution: 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[1])
# four

Explanation: The code uses the key argument and passes a lambda function into it.

The list.sort() method takes another function as an optional key argument that allows you to modify the default sorting behavior.

Explanation Key Argument

The key function is then called on each list element and returns another value based on which the sorting is done. Hence, the key function takes one input argument (a list element) and returns one output value (a value that can be compared).

Python List Sort Key Argument (Lambda Function)

There are two interesting features in the code you need to understand to fully grasp how it works:

  • How to sort lexicographically in ascending order .
  • How to use the lambda function.

Sorting in Ascending Order

First, 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'.

Using the Lambda Function

Second, 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.

Python List Sort Video

Related Puzzle

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:

Python list sort key puzzle

Exercise: What is the output of this puzzle?

Are you a master coder?
Test your skills now!

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!