lambda

Resources

  • Official sorting tutorial.
  • Sorting Real Python tutorial.
  • Real Python introduction to lambda functions.

lambda functions

Python lambda functions are anonymous functions.

For instance we could create an anonymous function that squares a number.

This function is not bound to a name, so we have no way of calling it directly.

Anonymous functions are usually used as arguments that we give to other functions. For instance, let’s image that we want to sort a list of words.

The sorting function uses the ASCII value of the letters to do the ordering, that’s why we get first the uppercase words, and then the lowercase ones. We’d like the sorted function to sort according to the lowercase version of each word, but we don’t want to alter the words themselves and that is exactly one of the uses of the lambda functions. We can pass to the sorted function a key argument with a function that will be called for every word and the ordering key will be the returned value of that function.

Lambdas are just a convenient way of writing small throw away functions. We could have written the previous code as:

So, lambdas are not really required, they are just syntactic sugar, but they are very commonly used when functions are passed as function arguments.