A lambda is a small function with no name. It saves you three lines when all you need is one expression.
If you have used def then you already know the idea, a lambda is the same thing written on one line.
lambda functions are versatile and particularly effective when used with data collections such as lists. They derive their name from the Lambda Calculus, which is foundational in theoretical computer science and programming language theory.
Lambda functions in Python
The only difference is the definition. Once you have the object, there is nothing to tell them apart.
f(x)
There’s no clear indicator of whether it’s a traditional function or a lambda one unless you view its definition.
Here’s a glimpse of a conventional Python function:
def f(x): |
The lambda version is one line. It can take as many parameters as you like, but the body stays a single expression.
Crafting Lambda Functions
The form is lambda parameters: expression. An expression, not statements.
lambda argument(s): expression
That is the one real limit: no statements, so no assignment and no loop. Just one expression that gives a value back.
Here’s an instance of a lambda function:
f = lambda x: x * x |
Further showing its versatility, consider another lambda function:
increment = lambda x: x + 1 |
Several parameters are fine:
product = lambda x, y: x * y |
Lambda is at its best with map, filter and sorted.
numbers = [1,2,3,4,5,6,7] |
Advantages of Using Lambda Functions
A lambda is worth it when the function is small and you only use it once. Without lambda you would write this:
def square(num): |
Opt for the more concise and readable lambda variant:
square = lambda x: x * x |
With lambda it is one line, and you can still see what it does.
If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.
