Bits N Bytes Banner

APR 26 2021


Affiliate Link:

Lambda’s are not barn animals, but are small anonymous functions that can be written in Python. They have any number of arguments and a single expression.

Here is lambda syntax:

lambda arguments : expression

You can create a number multiplier with a lambda as follows:

my_lamb = lambda x : x * 1000

To test this function you can call it with a print statement:


The displayed result will be 5000.

Multiple arguments are applied as follows:

my_lamb = lambda x, y, z : x * y * z
result: 125

Now you can recreate the one we built above with a more powerful technique.

def my_lamb(x):
    return lambda y : y * x

lamb_multiplier_1k = my_lamb(1000)

The answer again will be 5000. The parameters in the function definition (my_lamb) are used in the expression portion of the lambda. The lambda parameters (y) are used when we create a function from the lambda (ie - when we set a variable = to a call to the lambda function, then execute the function). The lambda is essentially an anonymous function within a function.

You could easily reuse the same function to do something like:

lamb_multiplier_25 = my_lamb(25)
result: 100

These are nice when you have a specific use case for them. Very convenient!!!