Member-only story
Python Lambda Functions Explained Simply
If you’re relatively newer to Python, you might be confused or intimidated by these fancy-sounding and fancy-looking stuff known as lambda functions. I’m here to tell you that there is nothing to be intimidated about!
Here’s a Normal Function
def add(a, b):
return a + b
The add
function takes in 2 arguments, and adds them together before returning it.
x = add(4, 5)
print(x)# this prints 9
If we call the function and pass 2 integer arguments inside, we get the sum of the 2 arguments a
and b
.
Here’s a Lambda Function
add2 = lambda a,b: a+b
This is a lambda function, and this does the exact same thing as the add
function defined previously.
x = add2(4,5)
print(x)# this also prints 9
Simply put, you can think of a lambda function as a normal function, but written in a different way
Syntax of a Lambda Function
lambda a,b : a+b
There are 4 parts to a lambda function:
- The
lambda
keyword - The input arguments