Python Lambda Functions¶
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
Syntax¶
Example¶
# A lambda function that adds 10 to the number passed in
x = lambda a : a + 10
print(x(5)) # 15
# A lambda function that multiplies two numbers
x = lambda a, b : a * b
print(x(5, 6)) # 30
Why use Lambda?¶
The power of lambda is better shown when you use them as an anonymous function inside another function.
It is often used with built-in functions like filter() and map():
mylist = [1, 2, 3, 4, 5, 6]
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, mylist))
print(evens) # [2, 4, 6]
Industry Context
Lambda functions are used for short, throwaway pieces of code that aren't worth defining with def.