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

Rate this post

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)
print(pairs)
# 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).

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.

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.