In Python, developers use lambda functions as anonymous, inline functions that can be defined and called on the fly without needing a separate function. Programmers commonly use lambda functions to pass functions as arguments to higher-order functions or to define simple, one-time-use functions.
In this article, we’ll be exploring Python lambda functions in-depth and how they work. We’ll cover their syntax, use cases, advantages, and limitations. Furthermore, we’ll provide practical examples to help us understand how to use lambda functions effectively in Python.
Python Lambda Function Syntax
People know the Lambda function in Python as an anonymous function that can have any number of arguments but can only contain expressions in its body.
Let’s take a closer look at the syntax of a lambda function and explore each characteristic in detail:
lambda arguments: expression
A lambda function can only contain expressions, which means it cannot include statements, such as print statements or assignments, in its body.
If we try to add a statement in a lambda function, it will raise a SyntaxError.
# Invalid syntax lambda x, y: print(x + y) # Valid syntax lambda x, y: x + y
One Line, One Shot
We write a lambda function as a single line of execution, which means we cannot include multiple lines of code in it.
However, we can include multiple expressions by separating them with commas.
Example of invalid Python lambda function syntax:
# Invalid syntax lambda x, y: x += 1 y += 1 return x + y # Valid syntax lambda x, y: (x + 1, y + 1)
Inference over Annotation
A lambda function does not support type annotations, which means we cannot specify the type of arguments or the return type of a lambda function.
However, Python can infer the type of arguments and the return type of a lambda function.
# Invalid syntax lambda x: int: x + 1 # Valid syntax lambda x: x + 1
Lambda on the Fly (IIFE)
We can immediately invoke or execute a lambda function, which means we can call it as soon as we define it.
This is also known as an Immediately Invoked Function Expression (IIFE) in Python.
# Invalid syntax (lambda x, y: x + y)(10, 20) # Valid syntax result = (lambda x, y: x + y)(10, 20) print(result)
Python Lambda Function Arguments
Python lambda functions can take any number of arguments, but they can only have a single expression. Developers often use lambda functions as a substitute for named functions when the function’s functionality is simple and a named function would be excessively complex.
The arguments to a lambda function are passed in the same way as they would be for a named function. They can be positional arguments, default arguments, variable-length arguments, or keyword arguments.
No Arguments, No Problem
A lambda function in Python can have any number of arguments, including zero arguments. Lambda function with no arguments performs a simple operation without needing any inputs.
# a lambda function that returns the string "Hello, World!" hello = lambda: "Hello, World!" print(hello()) # Output: Hello, World!
We use lambda functions with no arguments when we need to perform a simple operation that does not require any input from the user. We can use them in scenarios where we need to pass a function as an argument to another function, but the function itself does not require any arguments.
The lambda function takes positional arguments based on their position. This means that the first argument in the lambda function definition corresponds to the first argument passed to the function, the second argument in the lambda function definition corresponds to the second argument passed to the function, and so on.
# a lambda function that takes two positional arguments and returns their product product = lambda x, y: x * y print(product(2, 3)) # Output: 6
In the above example, we have defined a lambda function
product that takes two positional arguments and returns their product. We have called this lambda function and passed two arguments 2 and 3.
The lambda function specifies a default value for an argument using default arguments when the caller does not pass the argument. If the caller does not pass an argument to a lambda function that has a default value, the function uses the default value.
# a lambda function that takes one positional argument and one default argument power = lambda x, y=2: x ** y print(power(3)) # Output: 9 print(power(3, 3)) # Output: 27
In the above example, we have defined a lambda function
power that takes one positional argument and one default argument. If we do not pass the second argument, the default value will be 2. We have called this lambda function with only one argument in the first case, and with both arguments in the second case.
In a lambda function, we use variable-length arguments to accept an arbitrary number of arguments. We denote the variable-length argument by an asterisk (*) before the argument name. This enables the lambda function to accept any number of arguments that someone passes to it.
# a lambda function that takes a variable-length argument and returns the sum of all the numbers sum_lambda = lambda *args: 0 if len(args) == 0 else args + sum_lambda(*args[1:]) print(sum_lambda(1, 2, 3, 4)) # Output: 10
In the above example, we have defined a lambda function
sum that takes a variable-length argument and returns the sum of all the numbers passed to it.
Lambda functions use keyword arguments to pass arguments by name rather than position. This allows the caller of the function to pass arguments in any order, which can make the function easier to use.
# a lambda function that takes two keyword arguments and returns their difference difference = lambda x, y: x - y print(difference(y=2, x=5)) # Output: 3
Python Lambda vs. Regular Function
Python offers two primary ways to define functions: Lambda functions and regular functions. While they share a common purpose of executing code, there are some key differences between the two.
Let’s compare Lambda functions and regular functions side by side:
|Features||Lambda Functions||Regular Functions|
|Declaration||Defined using the ||Defined using the |
|Naming||Anonymous functions with no direct reference or reuse||Named functions that can be referenced and reused|
|Body||Restricted to a single expression||Can contain multiple statements|
|Complexity||Ideal for simple, one-off tasks||Suitable for complex logic and extensive computations|
|Reusability||Cannot be directly referenced or reused||Can be called multiple times in the code|
|Use Cases||Often used in higher-order functions and functional programming||Widely used throughout the codebase|
Python Decorator with Lambda Function
In Python, a decorator is a function that takes another function as input, performs some action on it, and returns a modified version of the function. Developers use Decorators to modify functions’ behavior without changing their source code.
We can use lambda functions with decorators to modify the behavior of a function in a concise and compact way. Additionally, we can use them to create decorators on the fly, without needing to define a separate function.
Let’s see an example of a decorator that uses a lambda function to modify the behavior of a function.
def uppercase(function): def wrapper(): return function().upper() return wrapper # Lambda function def lowercase_decorator(function): return lambda: function().lower() # Decorator to a function @lowercase_decorator def hello(): return "HELLO WORLD" # Calling Decorated Function print(hello()) # Output: hello world # Passing Lambda in Decorator function print(uppercase(lambda: "hello world")) # Output: HELLO WORLD
How Closures Works in Lambda Function?
In Python, a closure enables a function object to access variables in its enclosing lexical scope, even if someone calls the function outside that scope. This means that a closure allows a function to remember and access the values of the variables in its enclosing scope, even after the scope has been destroyed.
A nested function creates a closure by referencing a value from its surrounding scope. In the situation of lambda functions, the enclosing scope is the scope where the lambda function is defined.
Let’s take an example to understand this concept better:
def outer_func(x): def inner_func(y): return x + y return inner_func closure_func = outer_func(10) print(closure_func(5)) # Output: 15
In the above example, we have defined an outer function
outer_func that takes an argument
x. This function defines an inner function
inner_func that takes an argument
y and returns the sum of
y. The outer function returns the inner function, which is assigned to a variable
When we call
closure_func with an argument of 5, it returns the sum of 10 (which is the value of
x in the outer function) and 5, which is equal to 15.
In this example, the inner function
inner_func is a closure because it has access to the variable
x in its enclosing scope, even though that scope has been destroyed (after the outer function has returned).
Similarly, we can create closures using lambda functions.
def outer_func(x): return lambda y: x + y closure_func = outer_func(10) print(closure_func(5)) # Output: 15
In this example, the lambda function is a closure because it has access to the variable
x in its enclosing scope (which is the scope of the
Exception Handling in Lambda Function
The syntax for exception handling in a lambda function is the same as in a regular function.
lambda arguments: try_expression if condition else raise Exception("Error Message")
try_expression is the expression that will be evaluated if the
except_expression will be evaluated. The
condition is a Boolean expression that determines whether the
try_expression or the
except_expression should be evaluated.
# an example of a lambda function that handles ZeroDivisionError div = lambda x, y: x/y if y != 0 else raise Exception("ZeroDivisionError: Cannot divide by 0") print(div(10, 5)) # Output: 2.0 print(div(10, 0)) # Output: ZeroDivisionError: Cannot divide by 0
Use Cases of Python Lambda Functions
Lambda functions use various scenarios in Python, including:
- Filtering: You can use Lambda functions to filter sequences based on a condition.
- Mapping: You can use Lambda functions to transform sequences by applying a function to each element.
- Sorting: You can use Lambda functions to sort sequences based on a specific criterion.
- Reducing: You can use Lambda functions to reduce sequences to a single value by applying a function repeatedly.
Let’s explore these use cases in more detail with some practical examples.
Filter Using Python Lambda Functions
In Python, we use the built-in filter() function to filter a sequence based on a condition by selecting specific elements.
The filter() function takes two arguments: a sequence and a function. The function takes one argument and returns a Boolean value that indicates whether the element should be included in the filtered sequence.
Here is an example that uses a lambda function to filter even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
[2, 4, 6, 8, 10]
Map Using Python Lambda Functions
Mapping is the process of transforming a sequence by applying a function to each element.
In Python, the built-in map() function is used to apply a function to each element of a sequence.
The map() function takes two arguments: a function and a sequence. The function takes one argument and returns the transformed value.
Here is an example that uses a lambda function to double each element in a list:
numbers = [1, 2, 3, 4, 5] doubled_numbers = list(map(lambda x: x * 2, numbers)) print(doubled_numbers)
[2, 4, 6, 8, 10]
In this example, we first define a list of numbers. We then use the map() function with a lambda function that takes an element x and returns the doubled value of x.
Sort Using Python Lambda Functions
In Python, you use the built-in sorted() function to sort a sequence based on a specific criterion by arranging elements in a sequence.
The sorted() function requires two arguments: a sequence and a key function. The key function takes one argument and returns the value that determines the order of the elements in the sorted sequence.
Here is an example that uses a lambda function to sort a list of tuples based on the second element of each tuple:
fruits = [('apple', 3), ('banana', 2), ('cherry', 4), ('date', 1)] sorted_fruits = sorted(fruits, key=lambda x: x) print(sorted_fruits)
[('date', 1), ('banana', 2), ('apple', 3), ('cherry', 4)]
Reduce Using Python Lambda Functions
Reducing is the process of applying a function repeatedly to a sequence to obtain a single value. The reduce() function takes two arguments: a function and a sequence.
The function takes two arguments and returns the result of applying the function to the two arguments.
Here is an example that uses a lambda function to calculate the product of a list of numbers:
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product) # 120
Advantages of Using Python Lambda Functions
Lambda functions have several advantages in Python, which are as follows:
- Conciseness: Lambda functions are concise and require less code than traditional functions.
- Readability: Lambda functions can be more readable than traditional functions when the function is short and simple.
- Flexibility: Lambda functions make higher-order functions more flexible since they can pass them as arguments, unlike traditional functions.
- No side effects: Lambda functions don’t have side effects, which means that they don’t modify the state of the program outside their scope.
Limitations of Lambda Functions in Python
Lambda functions have some limitations in Python, which are as follows:
- Limited Functionality: Lambda functions can only contain a single expression and cannot contain statements or annotations.
- Lack of Readability: Lambda functions may become unreadable when they are complex or nested inside another function.
- No Documentation: Lambda functions cannot have documentation strings, which can make it difficult to understand their purpose and usage.
Congratulations, fellow developer! You’ve successfully explored the fascinating realm of Python Lambda functions. Armed with this knowledge, you now possess a powerful tool to simplify your code, increase your efficiency, and add a touch of elegance to your Python programming projects.
Remember, Lambda functions are not meant to replace regular functions but to complement them in specific scenarios. So, go forth and wield the power of Lambda functions wisely, and may your code be concise, efficient, and delightful to work with!
Feel free to share your experiences, questions, or any Lambda function magic tricks you’ve discovered along the way in the comments below. Happy coding, and until we meet again on this journey of discovery!
- Python lambda function official documentation: https://docs.python.org/3/reference/expressions.html#lambda