Lambda functions, also known as anonymous functions, are an alternative way of defining functions. Unlike regular functions, lambda functions do not have a name.
In general, they are small functions, and are used in contexts where a function is needed temporarily. For example, when used as parameters for other functions.
Lambda Functions
In Python, lambda functions are defined using the lambda
keyword followed by a list of parameters, followed by a colon (:
) and an expression.
lambda parameters: expression
For example, we can define a lambda function that calculates the square of a number as follows:
square = lambda x: x * x
This lambda function takes an argument x
and returns the result of x * x
. Lambda functions are especially useful when we need to pass a function as an argument to another function, as we will see next.
Lambda Functions with Multiple Arguments
In this example, sum
is a lambda function that takes two arguments x
and y
and returns the sum of both.
# Syntax: lambda arguments: expression
sum = lambda x, y: x + y
print(sum(3, 5)) # Output: 8
Examples
Let’s see some examples of how the syntax of lambda functions is used in Python:
Sum of Two Numbers
In this example, we define a lambda function called sum
that takes two arguments x
and y
and returns their sum.
sum = lambda x, y: x + y
print(sum(3, 5)) # Output: 8
Filtering a List
In this example, we use a lambda function within the filter()
function to filter the even numbers from a list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4, 6, 8, 10]
Mapping a List
In this example, we use a lambda function within the map()
function to calculate the square of each number in a list.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
Lambda Functions vs. Defined Functions
Lambda functions are useful when we need a quick function to perform a simple operation. They are often used in combination with higher-order functions, such as map()
, filter()
, and reduce()
.
- Syntax Limitations: Lambda functions are limited to a single expression and cannot contain multiple statements or lines of code.
- Readability: Lambda functions can affect the readability of the code if used excessively or in complicated situations.
- Debugging: Debugging lambda functions may be more difficult compared to functions with explicit names.
In summary, they are very useful for what they are, but don’t use them too liberally 😉