Lambda functions, also known as anonymous functions, are an alternative and concise way to define functions. As their name suggests (unlike regular functions) lambda functions do not have a name.
Generally, they are small functions and are used in contexts where a function is needed temporarily (for example, when used as parameters for other functions).
If you want to learn more, check out the Introduction to Programming Course
Lambda functions
In Python, Lambda functions are defined using the keyword lambda followed by a parameter list, 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 one argument
x - Returns the result of
x * x.
Lambda functions with multiple arguments
In this example, sum is a lambda function that takes two arguments x and y and returns their sum.
# Syntax: lambda arguments: expression
sum = lambda x, y: x + y
print(sum(3, 5)) # Output: 8
Practical examples
Let’s see some examples of how lambda function syntax is used in Python:
Sum of two numbers
In this example, we define a lambda function named 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
Lambda functions are especially useful when we need to pass a function as an argument to another function.
In this example, we use a lambda function inside the filter() function to filter 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 inside 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 code readability if overused or used in complicated situations.
- Debugging: It can be more difficult to debug lambda functions compared to functions with explicit names.
In summary, they are very useful for what they are, but don’t use them recklessly either 😉
