Background on Lambda Functions
Usually, a function in Python uses the def
statement. Python also provides an expression form that generates function objects. However, it returns the function instead of assigning it to name. That’s why they are known as anonymous (unnamed) functions or lambda functions. The origin of the name comes from a similar tool in the Lisp language which originates from lambda calculus. You may find it intimidating but it’s really not! In Python, lambda
just a keyword that introduces the expression syntactically.
lambda
is an alternative way to code a function, without the need to have full statements, decorators, or annotations. Generally, lambda
is very handy as a shorthand that allows you to embed a function definition within the code that uses it. Note that it’s entirely optional and you can always use def
instead.
A key point is this: lambda
is an expression, not a statement. Hence, it can appear in places a def
is not allowed by Python syntax. For a def
, a function can be referenced by name but must be created elsewhere. lambda
returns a value that is a new function which can optionally be assigned a name. Here are 10 examples of how we can use lambda
.