Lambda function in Python

Lambda function in Python
Photo by James Harrison / Unsplash

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Example 1:

# Add 10 to argument a, and return the result
x = lambda a: a + 10
print(x(5))

# Output:
# 15

Example 2:

# Multiply argument a and b and return the result
x = lambda a, b: a * b
print(x(5, 6))

# Output:
# 30

Example 3:

# Reuse a lambda function with unknown parameter
def multipiler(n):
    return lambda a: a * n


m2 = multipiler(2)
print(m2(1000))
m3 = multipiler(3)
print(m3(1000))
m10 = multipiler(10)
print(m10(1000))

# Output:
# 2000
# 3000
# 10000