A lambda function is a small, anonymous function that can be defined in a single line of code. In Python, "anonymous" means the function is created without a name (unlike a standard function defined with the def keyword).
Here are the key characteristics of lambda functions:
1. Simple Syntax
The basic structure is:
lambda arguments : expression
- Keyword:
lambda - Arguments: Just like regular functions, they can have one or many (separated by commas).
- Expression: A single piece of code that is executed and automatically returned. You don’t need to write the
returnkeyword.
2. Comparison with def
A lambda is essentially a shortcut for a simple function.
Standard way:
def square(x):
return x * x
Lambda way:
square = lambda x: x * x
3. Why use them?
Lambdas are best used for temporary tasks where you don't want to go through the effort of writing a full function definition. Common uses include:
- Passing functions as arguments: Many Python functions (like
sorted(),map(), orfilter()) expect another function as an input. Lambdas are perfect for this. - Closures: As seen in your experiment, they can "capture" variables from a parent function (like
ninmake_adder). - Readability: For very simple logic, keeping the code on one line can sometimes make the main logic easier to follow.
4. Limitations
- They can only contain one single expression. You cannot use loops, multiple lines of logic, or
if/elseblocks (unless you use a ternary operator). - They are harder to debug because they don't have a name in error messages (it will just say
<lambda>).
Labby's Tip: If your logic is complex or spans multiple lines, always use def. Use lambda only for simple, one-off transformations!