Lambda Functions

Lambda Functions in Python are an easy way to make one-off anonymous functions you don’t plan to use again.

They have very simple syntax rules but can be very powerful.

The basic syntax is as follows:


# If you wanted to cube a number, here is a way to do it as a function

def cube(x):
    return x*x*x

# And this is how to do it as a lambda function
lambda_cube = lambda x: x*x*x

print(cube(6))
print(lambda_cube(6))

Output:

216
216

Example: Iterate over list

numbers = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

doubles = list(map(lambda x: x*2, numbers))

print(doubles)

Output:

[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

Example: Function Set

pipeline = [lambda x: x**3 - 1 + 7,
            lambda x: x**10 - 2 + 4,
            lambda x: x**128 - 1 + 3]

for f in pipeline:
    print(f(2))

Output:

14
1026
340282366920938463463374607431768211458