Basics for lambda
lambda is a keyword in Python. We use it to create an anonymous function. So we also call lambda functions as anonymous functions.
But what is the anonymous function?
A normal function defined like this:
From the result, sum_two is the name of the defined function, it’s type is ‘function’.
Compared to normal function, an anonymous function is a function without a user-defined name.
Anonymous people sometimes get generic names such as ‘Anonymous’ or ‘Jane Doe’. In CPython, lambda functions get the generic pseudoname ‘
The benefits of lambda
But why we want to give a generic pseudo-name to some functions?
Naming is too damn hard! Think about how much time you spent on naming(variables, functions, classes) when you are programming.
Not all functions deserved a user-defined name.
Some functions are used temporarily, and we won’t need them later. We use a lambda function to saving time for naming and get better readability.
Suppose we need to add 2 to each element in a list, instead of use normal function:
We could use
lambda to finish the same computation in one line:
This is simplicity. We can write a lambda function with no hassle.
There are other functions like
sorted, they receive lambda function as a parameters.
The pitfall of lambda
The purpose of
lambda function is to improve the code’s readability. So if the logic of a function is not simple, we should not use lambda.
A simple rule is: don’t use lambda for the functions whose lengths are more than one line.
Think about this code snippet, could you understand this code easily?
This code is difficult to understand. The intention of this code is to get all the subsets from a
In this case, we should use a normal function with a proper name:
Explicit is better than implicit.
– Zen of Python
Remember, if we can’t make code clearer and shorter with lambda functions, then we need to use conventional ways to define functions.