What Are Python Lambda Functions, Anyway? | by Eric Kleppen | Jun, 2022

Learn to write Python like the pros by using lambda functions

Photo by Anete Lūsiņa on Unsplash

Traveling the road from rookie to Pythonista can take a while and varies from person to person. Most people start learning Python by reviewing the basic data structures for numbers, Booleans and strings, and then move to complex data structures like lists and dictionaries. From there you learn loops and if/else control logic, and eventually learn to write reusable code via functions.

Once you start exploring functions, you’ll come across lambda functions which can seem pretty intimidating at first. Similarly to list comprehensions, lambda functions allow you to write succinct code. Often something that would take several lines as a defined function can be done in one line using a lambda function!

Typical Python functions are simply a self-contained set of instructions designed to perform a specific task. They are important to master and understand because they allow us to keep code organized by breaking it into smaller, reusable chunks. If we’re writing a large program, utilizing functions can make the code easier to read and debug too.

In Python, we define a function using the def keyword, then give the function a name along with any necessary arguments that impact the function body’s execution. Often times, the return keyword is used to terminate the function and return the desired output to whatever called the function. Here is an example function:

#python example function
def my_function(string):
return print(string)
test my_function

The example my_function takes a string as an argument and prints the string as the returned output.

To take your Python skills to the next level, you need to master both normal functions and lambda functions. Lambda functions are great for making code shorter and more concise, which is the way of the Pythonista! We’ll take a look at a few simple examples to review the syntax, and then look at some actual use cases for lambda functions that will make you look like a pro.

As we see in the previous example, normal functions are defined using def and given a name. Lambda functions are defined using the lambda keyword and are nameless. They are anonymous functions that are not defined in any namespace, and they are intended for single use.

When I first learned about lambda functions, it seemed a bit tricky to wrap my head around. The syntax can feel confusing since a lambda function can take any number of arguments, but can only have one expression. Here are a couple simple examples:

#lambda syntax
#lambda <arguments> : <return expression>
#simple example
lambda_example = lambda x: x + x
#multiple arguments example
multiple_arguments = lambda x, y, z: (x + y) * z
Testing lambda function examples

Notice the multiple arguments are separated by commas. When calling the function, the caller provides the arguments. The return expression is defined after the colon (:). There is a single return expression, but the return expression can be simple or complex. It could even be another function, which makes lambda functions a powerful tool in your Python programming toolbox.

Let’s take a look at how we can use lambda to write functions the Pythonic way. Below we have a function that checks a list of strings for the word “two.” It returns the list of strings along with True or False depending on whether the word was in the strings:

sentences = ['Sentence one.', 'Sentence two.', 'Sentence three.']def contains_two(text):
answers = []
for s in txt:
if 'two' in s:
answers.append(True)
else:
answers.append(False)
return zip(answers, text)
Testing contains_two function

Instead of defining a function and using a for loop to go through the list, we can rewrite this succinctly using Python’s map() function along with a lambda function.

contains_two_lambda = map(lambda x: (True, x) if 'two' in x else (False, x), sentences)
Testing contains_two_lambda function

The map() A function takes a function and a sequence as arguments, running the function on the given sequence. The function we pass to map() is a lambda function, allowing us to perform the same thing our defined function does in only one line of code!

Lambda functions work well with functions like map(), reduce(), and filter(), three built-in Python functions that take a function as arguments. Lambda functions are also popular in data munging as they can work well with pandas dataframes. They can make applying logical operations to columns and rows concise one-liners.

As an analyst, I find myself using Pandas DataFrames all the time. Since DataFames are a popular data structure, let’s take a look at how easy it is to use lambda functions for transforming data in dataframes. Let’s create a simple pandas dataframe with some mock data:

#import dependencies
import pandas as pd
#create dataframe
df = pd.DataFrame({
'Occupation': ['Data Tech','Sales','Analyst','Engineer'],
'Name': ['John Smith', 'Jodie Whales', 'Eric Kleppen', 'Richard Heart'],
'Salary': [50000, 75000, 80000, 100000],
'YearsAtCompany': [2, 3, 1, 3],
})
Example dataframe

Next, let’s create a new column called newSalary using a lambda function. If I’m giving out raises based on the column YearsAtCompany and want to see what a person’s new salary will be, I can use the apply() function similar to how we used map() in the previous example:

df['newSalary'] = 
df['Salary'].apply(lambda x: x * (1 + df['YearsAtCompany']/10))
Verifying newSalary column

Notice that the apply() function takes the lambda function as an argument and applies the function to each row in the Salary column. The expression in the lambda function uses YearsAtCompany to determine the size of the raise.

Writing Python like a pro takes practice, so don’t worry if you feel intimidated by new concepts like lambda functions. The syntax looks strange, but lambda functions allow you to write concise, one-time-use functions that are great for applying logical operations.

Although they can only perform one expression, the expression can be complex and even include another function. Lambda functions can work well with a series of data, as even data structures like Pandas DataFrames.

Leave a Comment