Lambda Expressions
One of my favourite python feature is “Lambda Expressions”.
Its a very useful and powerful feature. You will use it in your Data science exploratory data analysis as well.
Lets get started:
Let me show you the intitution behind Lambda expression:
#Your normal sum function
#very simple funtion, takes two inputs and returns the sum of both
def add(x,y):
return x+y
#Calling the add function
print(add(2,3))
5
Now lets see how would we implement the same “add” function via Lambda:
add = lambda x,y:x+y
#<function_name> = lambda <param1>,<param2>:<return expression without the keyword return>
#return keyword in not needed in lambda
print(add(2,3))
5
Thats it. It is that simple. You will see the power of that expression later in future python tutorials as well.
Three input parameters in Lambda
Taking it a step further and implementing lambda for three input parameters
add = lambda x,y,z: x+y+z
add(2,3,4)
9
If-else in Lambda
Lambda expression with single if-else:
#Normal even_odd funcion
def even_odd(x):
if x%2==0:
return 'even'
else:
return 'odd'
even_odd(21)
'odd'
even_odd(22)
'even'
#Lambda implementation of the same function
even_odd = lambda x:'even' if x%2==0 else 'odd'
even_odd(2)
'even'
even_odd(3)
'odd'
Nested if-else in Lambda
You can even go a step further to implement a nested if-else in lambda, but be careful with it as alot of experts don’t recommend it this way because the deeper you go, the messier your code will get and it would leave a person reading your code confused.
#Check if two numbers are equal or not
def equality_check(x,y):
if x>y:
return 'Not equal'
elif x<y:
return 'Not equal'
else:
return 'equal'
equality_check(2,1)
'Not equal'
equality_check(50,50)
'equal'
Now lets implement the same function in Lambda
equality_check = lambda x,y: 'Not equal' if x>y else ('Not equal' if x<y else 'equal')
equality_check(4,4)
'equal'
equality_check(5,4)
'Not equal'
equality_check(4,5)
'Not equal'
I wouldn’t recommend a nested if-else in Lambda. Rather a normal funcion approach would be much better in that case.
Reversing a string via Lambda expression
reverse = lambda s:s[::-1]
reverse('hello world')
'dlrow olleh'
Grabbing first letter of a string
first = lambda s:s[0]
first('hello world')
'h'
Leave a comment