Lambda Functions
Earlier we quickly covered the most common way of defining functions, the def
statement. You'll likely come across another way of defining short, one-off functions with the lambda
statement. It looks something like this
This lambda function is roughly equivalent to
So why would you ever want to use such a thing? Primarily, it comes down to the fact that everything is an object in Python, even functions themselves! That means that functions can be passed as arguments to functions.
As an example of this, suppose we have some data stored in a list of dictionaries:
Now suppose we want to sort this data. Python has a sorted
function that does this:
But dictionaries are not orderable: we need a way to tell the function how to sort our data. We can do this by specifying the key
function, a function which given an item returns the sorting key for that item:
Output
While these key functions could certainly be created by the normal, def
syntax, the lambda
syntax is convenient for such short one-off functions like these.
Last updated