Beyond the Basics: Functions

3.2. Beyond the Basics: Functions#

Sometimes you want to use the same code multiple times, so you could embed this code into a function. However, sometimes the code you want to use is so short that putting it into a function feels a bit over the top. This is where lambda functions are useful.

Lambda functions are functions that can take any number of arguments but can only have one expression in their function body. To demonstrate, see the code below. Here we have two functions that do exactly the same, but one is a lambda function and the other one is a normal function.

sqrt_lambda = lambda x : x**0.5

def sqrt(x):
    sqrt = x**0.5
    return sqrt

print(f"The square root of 16 is equal to {sqrt_lambda(16):.0f}")
print(f"The square root of 16 is equal to {sqrt(16):.0f}")
The square root of 16 is equal to 4
The square root of 16 is equal to 4
As you can see, the lambda version is much more concise. It automatically returns the computed value for you as well.