Lambda Functions in Python
The Basic Syntax
Lambda functions, also known as anonymous functions, are a flexible tool for creating small, throwaway functions. They're incredibly useful when we need to pass a function as an argument to another function, and we don't want to define a separate one in our code.
Unlike regular functions in Python, which are defined using the
def keyword, we denote lambda functions with the
A lambda function accepts any number of arguments but only evaluates and returns one expression.
lambda arguments: expression
Observe the following lambda function that adds two numbers:
add = lambda x, y: x + y print(add(3, 4)) # Output: 7
As you can see, we have defined a lambda function
add that takes two arguments
y. The body of the function contains a single expression
x + y returning the sum of
Additionally, we can include multiple arguments. For instance, we can create a lambda function that calculates the product of three numbers, like so:
multiply = lambda x, y, z: x * y * z print(multiply(2, 3, 4)) # Output: 24
Combining Regular and Lambda Functions
Let's demonstrate how a regular function can return a lambda function that performs a specific operation. Moreover, we'll see how we can create multiple instances of the same lambda function with different behaviors by calling the regular function with different arguments.
def create_function(n): return lambda x: x + n add_5 = create_function(5) add_10 = create_function(10) print(add_5(3)) # Output: 8 print(add_10(3)) # Output: 13
In the example above, we have a regular function named
create_function that takes in an argument
n, and returns a lambda function that takes an argument
x and calculates the sum of
We then use
create_function to create two separate instances of the lambda function,
add_10, by calling it with different arguments,
Why Use a Lambda Function?
The Python style guide, PEP 8, states that it is always preferred to use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier. Frankly, regular functions are less limited than lambdas and in turn offer more benefits and should be used whenever possible.
Another disadvantage of lambda functions is that they can be difficult to debug. Since they are anonymous, it can be challenging to trace when an error occurs.
However, that doesn't mean that lambda functions can't provide neat solutions. The key is to use them judiciously, and only when there is nothing more "Pythonic" available to us.
Lambda Functions on Iterables Objects
The most appropriate use of lambda functions would probably be in iterable objects alongside functions such as
reduce(), to name a few. With this combination, we can loop over lists, tuples, and dictionaries, and greatly simplify our code.
map() with Lambda Functions
map() function takes a function and an iterable object as arguments, and returns a new iterable object with the function applied to each element.
To demonstrate, we'll use an example where we square each element in the list:
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x**2, numbers)) print(squared_numbers) # Output: [1, 4, 9, 16, 25]
filter() with Lambda Functions
filter() function takes a function and an iterable object as arguments, and returns a new iterable object containing only the elements for which the function returns
We can potentially use it in combination with a lambda function to filter a list and find all even numbers:
numbers = [1, 2, 3, 4, 5] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # Output: [2, 4]
reduce() with Lambda Functions
reduce() function takes a function and an iterable object as arguments, and returns a single value that is the result of applying the function to the elements of the iterable object.
We can use it with a lambda function to calculate the product of all numbers in the list, like so:
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product) # Output: 120
While lambdas have some drawbacks, they can potentially be a neat addition to any Python programmer's toolkit. They provide a way to create simple, one-off functions for specific tasks. However, they should be used with care and only when there is no better alternative present.
If you need a refresher, take the time to familiarize yourself with the basics of functions in Python found below, alongside other useful resources. As always, don't be afraid to experiment and see how you can potentially utilize lambda functions in your projects.
The Basics of Python Functions
Official Python Style Recommendations