The Way of the Serpent

Pythonic Tips & Tricks — Working with Lambda

How to apply the Lambda function in Python

Tonichi Edeza
Towards Data Science
4 min readFeb 9, 2021

--

Photo by Tim Marshall on Unsplash

One of the most interesting aspects of the Python language are Lambda functions. For programmers who are skilled at reducing their codes into simple logical statements, Lambda functions help shrink the number of lines dramatically. In this article we shall go over what Lambda functions are and how to apply them in practical ways in Python.

Let’s begin!

The Benefits of Lambda

Say you have a function that multiplies any number you put into it by 10.

def mult_ten(original):
return original * 10
number = mult_ten(5)
Function Output

The function can actually be written as a literal one-liner. This is achieved through the use of lambda.

mult_ten = lambda i : i * 10
print(mult_ten(5))
Exactly the Same Output

But wait, how about more complex functions such as the one below:

def mult_int(original, multiplier):
return original * multiplier
number = mult_int(5, 11)
Output of Two Variable Function

This can also be condensed into a lambda function.

mult_int = lambda i, j : i * j
print(mult_int(5, 11))
Exactly the Same Output

In fact we can have as many variables as we want. Below is an example of a much more complicated function.

def complicated_function(a, b, c, d, e):
return ((a+b) / (c+d)) * e
number = complicated_function(1, 2, 3, 4, 5)
Output of Complicated Function

Again we can condense this entire function into a lambda function.

complicated_function = lambda i,j,k,l,m : ((i + j) / (k + l)) * m
print(complicated_function(1, 2, 3, 4, 5))
Exactly the Same Output

Applying Lambda Functions with IF-ELIF-ELSE Logic

Of course we are not limited to purely mathematical operations. We can use If-Else statements to create much more interesting functions. Take the below function for example. It classifies a number as being whether Odd or Even.

def odd_even(figure):
if figure % 2 == 0:
return 'Number is Even'
else:
return 'Number is Odd'
number = odd_even(2)
Function Output

This too can be collapsed into a one-line lambda function.

odd_even_lambda = lambda i: 'Number is Even' if i % 2 ==0 
else 'Number is Odd'
new_num = odd_even_lambda(3)
Correct Output

Let us now try to incorporate an elif element. The below function will tell us if the number is Negative, Positive, or Zero.

def pos_neg(figure):
if figure < 0 :
return 'Number is Negative'
elif figure == 0:
return 'Number is Zero'
else:
return 'Number is Positive'
print(pos_neg(-1))
print(pos_neg(0))
print(pos_neg(1))
Function Output

There is actually no direct way to incorporate the elif element into a lambda function. But we can essentially achieve the same effect by using a nested if.

pos_neg_lambda = lambda i: 'Number is Negative' if i < 0  else ('Number is Zero' if i == 0 else 'Number is Positive')
print(pos_neg_lambda(-2))
print(pos_neg_lambda(0))
print(pos_neg_lambda(2))
Exactly the Same Output

Applying Lambda to Panda DataFrames

Of course to truly appreciate the power of lambda, we have to see it in action. Below is a sample of a DataFrame created via NumPy and Pandas.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(-10,11,1))
df.head(5)
Constructed DataFrame

Using the power of lambda, we can create new columns with elements based on the reference column.

df['number_type'] =  df[0].apply(odd_even_lambda)
df['number_sign'] = df[0].apply(pos_neg_lambda)
Edited DataFrame

With just two lines of code we were able to generate new columns for the DataFrame. This showcases the lambda function’s strength of being able to apply logic onto a large set of data in a succinct and elegant way.

In Conclusion

Lambda Functions are an incredibly powerful feature of the Python programming language. Frequently using them trains your mind to distill your programming logic down to its core elements. This is a skill that will help you not just in the Python programming language, but also in most programming languages. Though the examples we went over are quite basic, I hope they were enough to whet your appetite and get you accustomed to using lambda.

--

--