Lambda functions are in short, anonymous functions. Literally one-liners that would make you blush with praise.
They are functions you create when you want to perform operations in a simple expression, or for functions you're going to use just once.
Without further bickering, below is a function that squares a number:
def square(x: int) -> int: return x ** 2
With a lambda function, this can be expressed like so:
lambda x: x ** 2
While this would seem weird, the structure of a lambda expression is like so:
lambda <argument>: expression # or can have multiple arguments lambda <arg1>, <arg2>, ..., <argn>: expression
A lambda function does not have an explicit
return keyword because it automatically returns the result of the evaluated expression.
So, back to our square example, we can use the lambda function like so:
number = 3 # assigning like a variable and use square_lambda = lambda x: x ** 2 print(square_lambda(number)) # -> 9 # or use it as an IIFE (immediately invoked function expression) print((lambda x: x ** 2)(number)) # -> 9
Lambdas are like regular functions and can be used like one except it will only take one expression. So you can't write a multi-line expression as in a regular function.
They do not replace regular functions
Lambdas are for specific use cases and should not be abused to enforce one-liners or create puke-worthy expressions like this example below:
square = lambda x: x ** 2 four_squared = lambda x: square(square(x))
That said, you can assign them to variables, pass them to other functions as callables and use them as you wish.
They can be used as convinience functions for a lot of things especially in cases where you need to pass to a class or function, a callable that accepts 1 argument but your callable requires 2. An example is:
def power_up(number, exponent): return number ** exponent def transform(number: int, operation: Callable) -> Any: return operation(int) # you can pass a function that uses transform with a squaring function like so: print(transform(3, lambda x: power_up(x, 2)) # -> 9 # or a cube function print(transform(3, lambda x: power_up(x, 3)) # -> 27
Examples such as the above are needed in lots of Python libraries that expects you to pass a callable.
Use lambdas responsibly.