Blog Tech Programming Languages Getting Started With Lambda Functions in Python

Getting Started With Lambda Functions in Python

Sometimes programmers only use a function once, since they don’t want to clutter up their code with function definitions. Python’s lambda keyword lets you define a function in a single line of code and use it immediately.

In this article, we’ll walk you through writing lambda functions in Python. You’ll learn when to use them. You’ll see real-world examples of lambda functions used to process and filter lists of data.  

What Is a Lambda Function?

A lambda function, also called an anonymous or inline function, is a single line of code that evaluates an expression. Lambda functions can accept any number of parameters and will always return a value. 

Let’s compare a lambda function with a traditional function. If you’re a student of Python, you might recognize the traditional function:

def cube(num):
  return num * num * num

Here’s the lambda version of the same function:

lambda num: num * num * num

Both functions return the cube of a given number, but the lambda version is more compact. The lambda function also lacks a name, which is why you might see it called an anonymous function.

Next, let’s break down the syntax of a lambda function and look at a few variations.

Anatomy of a Lambda Function

Lambda functions use a streamlined notation, but all the parts of a regular Python function definition are still present. They also use an implicit return, and the only component that’s optional is the function name. 

Lambda Arguments and Syntax

In our previous example, we looked at a lambda function that took a single argument. Let’s try another lambda function, this time with multiple arguments, and see how the syntax changes. In this example, we’ll multiply two numbers together and add the third. Here’s the code: 

lambda x, y, z: x * y + z

In the code above, we create a lambda function with x, y, and z as arguments. We did so by specifying the lambda keyword, followed by the arguments, a colon, and the expression we’d like to evaluate. Here’s our lambda function broken down into components:

Every lambda function we write will have a similar syntax. Only the list of arguments and expression will change. 

Now that we know how to create lambda functions, let’s take a look at when we should use them in our code.

When Should We Use Lambda Functions?

You can use lambda functions in place of any regular function that evaluates a single expression and returns a value. So if your function needs to change a global variable, read from a file, or evaluate more than one expression, it will not work as a lambda function. Python programmers do, however, generally prefer lambda functions in certain cases. 

Map, Filter, and Reduce in Python

One of the most common use-cases for lambda functions is working with iterable objects. Python implements three functions called map, filter, and reduce that perform operations on lists of data. These three functions each take a function and a list as arguments. 

Unlike map and filter, reduce needs to be imported from the functools library.

Since lambda functions can be defined as they are needed, programmers prefer them in cases where a function is only used once. Let’s look at examples of map, filter, and reduce and see how you might use lambda functions.

Lambda Functions in Map

Python’s map function takes two arguments: a function and an iterable object. Python iterates through the object and runs the function against each item in the object. Map returns a list of results, and does not modify the original object.

Let’s see an example of the map function in action. We’ll pass in a list of tuples, and divide the first element in the tuple by the second element. Here’s the code:

data = [
  (50, 5),
  (20, 2),
  (30, 3),
  (60, 6)
result = map(lambda x: x[0] / x[1], data)
for item in result:
  print(f"Lambda returned the answer: {item}")

In the code above, we defined a list of tuples named data. Then we called the map function with our lambda function as the first argument and our list as the second argument. We wrote the lambda function to expect a tuple as an argument. It returned the value stored in element 0 of the tuple divided by the value stored in element 1.

After map runs, we’ll store the results in the variable result. We’ll then iterate through the list of results and print them. We expect the results of our division to be 10 in every case. After running the code, we can confirm the answer is indeed 10 for each set of data:

Now let’s move on to Python’s filter function.

Lambda Functions in Filter

The filter function works similarly to map in that it requires a function and list as arguments. Filter calls the function we pass on each item in the list, and returns the items our lambda function evaluates as true as output.

Let’s look at how we can use filter to find even-numbered list items. To do so, we’ll need to write a lambda function that’s true only when the number we pass to it satisfies our conditions. 

In this case, we’ll use the modulo operator to divide each list item by two and check the remainder. If the remainder is zero, we know the number is even. Here’s the code:

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = filter(lambda x: x % 2 == 0, data)
print(f"Lambda returned the answer: {list(result)}")

We pass in a list of the numbers one through ten, and then run the filter and store the result. Lastly, we print the result and get a list of the even numbers through ten:

Now that we’ve seen how to filter data using lambda, let’s move on to the reduce function.

Lambda Functions in Reduce

As a final example of using lambda functions as arguments, let’s look at the reduce function. Like map and filter, reduce takes a function as the first argument and a list as the second. Reduce is a cumulative function: It passes every list item into our lambda function and keeps a running total of the results.

In this case, we’ll use reduce to add all the items in the list together. Our lambda function will need to accept two arguments. The first argument, x, is the accumulator, and the second argument, y, is the list item that will be added, subtracted, multiplied, or divided with the accumulator. 

Let’s look at the code for Python’s reduce function using lambda:

from functools import reduce 
data = [10, 30, 50, 10]
result = reduce(lambda x, y: x + y, data)
print(f"Lambda returned the answer: {result}")

In this example, we add the list items together in our lambda expression. Reduce starts with an empty accumulator and adds the first item. It then sets the accumulator to the result of the first operation and repeats. If we add the numbers in our data, we should get an answer of 100:

Sure enough, reduce returned the correct answer.

Learn More With Udacity

In this guide, you learned to use Python lambda functions when writing a full function definition would be inefficient. Short functions that you’ll only use once are a good candidate for lambda. You should also consider lambda when passing functions as an argument—as in map, filter, and reduce.

To learn more about calling functions in Python, enroll in our Introduction to Programming Nanodegree. In this 4-month online course, you’ll learn the basics of Python and inch closer toward your dream programming job. No coding experience is required, so sign up today!

Stay updated on the latest in technology

"*" indicates required fields

Stay updated on the Latest in Tech

Be first to hear about special offers, news, and resources from Udacity

"*" indicates required fields