A Beginner’s Guide to Understanding Python Lambda Functions
Lambdas in Python are one of the most useful, important, and interesting features to know about. Unfortunately, they’re also easy to misunderstand and get wrong.
In this article, we’re going to explain everything you need to know about these mysterious functions, how to use them, and why they’re useful.
Before diving into these practical examples, you may wish to set up a Python virtual environment. If you don’t even want to do that, then you should at least try these examples with an interactive online Python shell.
What’s a Lambda in Python?
A lambda is simply a way to define a function in Python. They are sometimes known as “lambda operators” or “lambda functions”.
If you’ve used Python before, you’ve probably defined your functions using the def keyword, and it’s worked fine for you thus far. So why is there another way to do the same thing?
The difference is that lambda functions are anonymous. Meaning, they are functions that don’t need to be named. They are used to create small, one-off functions in cases where a “real” function would be too big and bulky.
Lambdas return a function object, which can be assigned to a variable. Lambdas can have any number of arguments, but they can only have one expression. You cannot call other functions inside lambdas.
The most common use for lambda functions is in code that requires a simple one-line function, where it would be overkill to write a complete normal function. This is covered in greater detail below, under “What About Map, Filter, and Reduce?”.
How to Use Lambdas in Python
Before looking at a lambda function, let’s look at a super basic function defined the “traditional” way:
def add_five(number):
return number + 5
print(add_five(number=4))
This function is very basic, but it serves to illustrates lambdas. Yours may be more complex than this. This function adds five to any number passed to it through the number parameter.
Here’s how it looks as a lambda function:
add_five = lambda number: number + 5
print(add_five(number=4))
Rather than using def, the word lambda is used. No brackets are required, but any words following the lambda keyword are created as parameters. The colon is used to separate the parameters and the expression. In this case, the expression is number + 5.
There’s no need to use the return keyword—the lambda does this for you automatically.
Here’s how you’d create a lambda function with two arguments:
add_numbers_and_five = lambda number1, number2: number1 + number2 + 5
print(add_numbers_and_five(number1=4, number2=3))
If you’re still unsure as to the point of lambdas, the next section will dive in and help you see the light.
Python Lambdas With Map, Filter, and Reduce
The Python core library has three methods called map, reduce, and filter. These methods are possibly the best reasons to use lambda functions.
The map function expects two arguments: a function and a list. It takes that function and applies it to every element in the list, returning the list of modified elements as a map object. The list function is used to convert the resulting map object back into a list again.
Here’s how to use map without a lambda:
list1 = [2, 4, 6, 8]
print(list1)
def add_five(number):
return number + 5
new_list = list(map(add_five, list1))
print(new_list)
This map function is quite handy, but it could be better. the add_five function is passed in as an argument, but what if you don’t want to create a function every time you use map? You can use a lambda instead!
Here’s what that same code looks like, only with the function replaced by a lambda:
list1 = [2, 4, 6, 8]
print(list1)
new_list = list(map(lambda x: x + 5, list1))
print(new_list)
As you can see, the whole add_five function is no longer required. Instead, the lambda function is used to keep things neat.
With the filter function, the process is much the same. Filter takes a function and applies it to every elemen in a list and created a new list with only the elements that caused the function to return True.
First, without lambdas:
numbers = [1, 4, 5, 10, 20, 30]
print(numbers)
def greater_than_ten_func(number):
if number > 10:
return True
else:
return False
new_numbers = list(filter(greater_than_ten_func, numbers))
print(new_numbers)
There’s nothing wrong with this code, but it’s getting a bit long. Let’s see how many lines a lambda can remove:
numbers = [1, 4, 5, 10, 20, 30]
print(numbers)
new_numbers = list(filter(lambda x: x > 10, numbers))
print(new_numbers)
The lambda function has replaced the need for the whole greater_than_ten_func! And it’s done it in five simple words. This is why lambdas are powerful: they reduce clutter for simple tasks.
Finally, let’s look at reduce. Reduce is another cool Python function. It applies a rolling calculation to all items in a list. You could use this to tally up a sum total, or multiply all numbers together:
from functools import reduce
numbers = [10, 20, 30, 40]
print(numbers)
def summer(a, b):
return a + b
result = reduce(summer, numbers)
print(result)
This example needs to import reduce from the functools module, but don’t worry, the functools module is part of the Python core library.
The story is very much the same with a lambda, there’s no need for a function:
from functools import reduce
numbers = [10, 20, 30, 40]
print(numbers)
result = reduce(lambda a, b: a + b, numbers)
print(result)
Things to Watch Out For With Python Lambdas
These examples have shown just how easy lambda functions are, along with map, filter, and reduce, from the Python core library. Still, there are a few uses where lambda functions don’t help.
If you’re doing anything more than a basic task, or want to call other methods, use a normal function. Lambdas are great for one off, anonymous functions, but they must only have a single expression. If your lambda starts looking like a regular expression, then it’s probably time to refactor in to a dedicated method.
For more tips, check our guide to object-oriented programming in Python and check out our FAQ guide for Python beginners.
Read the full article: A Beginner’s Guide to Understanding Python Lambda Functions