Python Lambda Functions
In Python, a lambda function is a small anonymous function defined with the keyword lambda
.
Lambda functions can have any number of arguments but only one expression. These functions are often used when a simple function is needed for a short period of time, typically in cases like filtering, mapping, or reducing data.
Lambda functions are a powerful feature in Python, allowing you to create small anonymous functions on the fly.
While they are limited to single expressions, their concise syntax makes them ideal for simple operations, especially when used with functional programming tools like filter()
, map()
, and reduce()
.
What is a Lambda Function?
A lambda function is a single-line function declared with the keyword lambda
. It can take multiple arguments but only has one expression.
The syntax for a lambda function is:
Syntax
lambda arguments: expression
Example 1: Using Lambda Function for Addition
add = lambda x, y: x + y
result = add(5, 3)
print("Sum:", result)
Output
Example 2: Using Lambda with filter()
Function
# Example: Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)
Output
Example 3: Using Lambda with map()
Function
numbers = [1, 2, 3, 4]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print("Squared numbers:", squared_numbers)
Output
Example 4: Using Lambda with reduce()
Function
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print("Product of all elements:", product)
Output
Note: The reduce()
function is available in the functools
module.
Advantages of Lambda Functions
- They can be used to write quick, throwaway functions without needing to formally define a function.
- They make the code shorter and more readable, especially for simple operations.
- Useful in functional programming paradigms like using
filter()
,map()
, andreduce()
.
Limitations of Lambda Functions
- They can only contain one expression, making them limited in functionality compared to regular functions.
- They are less readable if overused or used in complex expressions.