#22: Lambda Functions
Sometimes we need a callable object that we can use as an argument to a function. While we could create a function for that purpose, there is another way that needs less typing.
What is a lambda function?
Lambda functions, also known as anonymous functions, are functions without a name and only one statement. What sounds strange is indeed a great help when you combine it with built-in functions like filter() or map(). You not only save yourself a lot of typing, your code is simpler to understand when you have everything that goes on in front of you.
The syntax for a lambda function looks like this:
lambda arguments: expression
The lambda at the beginning is the keyword you must write; the arguments are the variables you want to use inside your expression. The arguments are optional, if you do not need them you write the : directly after lambda (lambda: expression). For lambdas you do not write return statements, that is done behind the scenes.
You can write a lambda function that checks if a number is even like this:
That will return True if the value we give in is even and False otherwise.
If we want to run our lambda in the REPL we may give it a name:
If you prefer a function instead, you could write it this way:
Where lambdas are a great help
We can combine lambdas with a wide range of other functions. If we want to filter a list, we can use our lambda from above like this:
Or we can use the map() function to modify values of a list without much effort:
In both examples we could use a function. However, the lambda is all we need and the readability of the code does not suffer.
Conclusion
Lambdas cannot substitute functions, but they are a great help when you just need a single expression as a parameter to another function.