# Sort tuples, and lambda usecase

```
my_list.sort(key=lambda x: x[1])
```

`key` is a function that will be called to transform the collection's items before they are compared. The parameter passed to `key` must be something that is callable.

The use of `lambda` creates an anonymous function (which is callable). In the case of `sorted` the callable only takes one parameters. Python's `lambda` is pretty simple. It can only do and return one thing really.

The syntax of `lambda` is the word `lambda` followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as `while`, `for`, `if` and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.

We can compare the use of lambda with that of def to create a function.

```
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2
```

lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.

`variable` is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sisyphus.gitbook.io/project/python-notes/sort-tuples-and-lambda-usecase.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
