In Python, functions provide several benefits. By creating a command you can reuse over and over you can write it once, then use it repeatedly in several places. This shortens the length of a program by avoiding duplication. Functions also provide a name to a command, which you can make descriptive. If a user reads something along the lines of
sort_alphabetically(list) they know that a list is about to be sorted alphabetically. Without that name, they’d dig through a few lines of code to figure out what’s happening.
That said, sometimes you don’t expect to reuse a function several times so formally declaring a function doesn’t make sense. Maybe you have a single data set and need to apply a calculation to all aspects of it once. Or maybe you need to pass a function as a parameter to another function. In these cases, it often isn’t worth the effort to formally declare a function.
Lambda Functions in Python
Instead, you can use an anonymous function — which we call a lambda function in Python.
What the Heck Is a Lambda Function?
Anonymous functions are what they sound like: they’re functions without names. Where you use these functions defines them but you don’t store them for future reference and can’t call them later. They’re one-time use functions. These functions tend to be quite simple, and more compact than formal function declarations — you write them on a single line.
In Python anonymous functions are referred to as lambda functions and you call them using the keyword
lambda. Lambda literally has no meaning other than to tell Python that you are about to define an anonymous function.
How Does a Lambda Function Work?
Since lambda functions are written on a single line of code they need to have specific syntax. This syntax takes the form of:
lambda input: function
That line has the following three features:
lambda: This is the keyword informing Python that the following information is a lambda function. Since this is a keyword with a specific meaning to Python this term cannot be changed.
input: This is the input to a function, and is similar to the x in function(x). This tells the lambda function what value to modify in the next part of the definition. The input term can be whatever value you desire. Since this is a temporary function many people don’t worry about specificity as much and simply use
xas a convention. Others are sticklers for clarity in code (I happen to be in that camp) and choose to use descriptive names.
function: This is where you define the function to be applied to the data set. If you want to return the square of numbers your function could be
x ** 2. Or if you want to calculate the sales tax, (assuming six percent) on items with known sales value (and are a stickler for clarity) your function could be
sales_value * 0.06.
Note the variable name you use (in this case either
sales_value) must match what’s listed in input. So, in this case, that would have to be
sales_valuedepending on which method you use.
Lambda Functions in Action
The main goal of a lambda function is to create a simple function that can act as an input to a separate function. Python and Pandas contain many methods that enable functions as inputs, enabling you to apply a function to large data sets at a time. One common example is pandas.apply().
With that in mind, let’s create a trivial example. To do this, let’s first write a function that accepts another function as an input. This function will be called
apply_to_list and will behave similarly to the
pandas.apply() function, but will work specifically on lists (I’ll simplify for the sake of the example).
def apply_to_list(list, f): return[f(x) for x in list]
This function accepts both a list and a function as an input. The function then uses a list comprehension to evaluate that function on each value in the list, stores that value in a new list and, after executing the function for all values in the list, returns a new list with the modified data.
Now we have a function that can apply any function we create to a list. This is an excellent opportunity to use a lambda function to perform some calculations. Let’s stick with our example of calculating sales tax based on known sales value.
First we create a list of data representing the value of different sales, then we pass it to
apply_to_list as a lambda function. You can do this as follows:
sale_value = [18, 24,5, 17, 21, 19] apply_to_list(sale_value, lambda sale_value: sale_value * 0.06)
This will calculate the sales tax for each item in sale_value, store it in a new list, and print that new list to the terminal. For this particular example the output will be
[1.08, 1.44, 0.3, 1.02, 1.26, 1.14].
One weakness in this implementation is that I hard-coded the sales tax to be six percent in the lambda function. A more flexible implementation would define the sales tax rate as a variable and reference that variable in the lambda function.
* * *
Anonymous functions are a great way to simply write a function that you only need to reference one time, especially when passing it to a different function as an input. Now you know how to write anonymous functions and can use them as inputs to other functions. Happy coding!