Python Lambda
A lambda function in Python is a small, anonymous function defined using the lambda keyword. Lambda functions are typically used for short, simple operations that can be defined in a single line of code. They are often used when a function is needed temporarily or when writing functions that are passed as arguments to higher-order functions (e.g., functions like map(), filter(), and sorted()).
Syntax of a Lambda Function:
lambda arguments: expression
- arguments: The parameters passed to the lambda function.
- expression: The expression or operation that is evaluated and returned when the lambda function is called.
1. Basic Example
A lambda function that adds two numbers:
add = lambda x, y: x + y
print(add(5, 3))
Output:
8
In this example, the lambda function takes two arguments (x and y) and returns their sum.
2. Lambda with Multiple Arguments
Lambda functions can take multiple arguments. Here’s an example of a lambda function that multiplies three numbers:
multiply = lambda x, y, z: x * y * z
print(multiply(2, 3, 4))
Output:
24
3. Lambda in Higher-Order Functions
Lambda functions are often used in higher-order functions like map(), filter(), and sorted() because they allow for compact and on-the-fly function definitions.
Example with map():
The map() function applies a given function to all items in an iterable (like a list). Here’s how you can use a lambda function with map():
numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
Output:
[1, 4, 9, 16]
In this example, the lambda function squares each element of the list.
Example with filter():
The filter() function filters the elements of an iterable based on a function that returns a Boolean value (True or False). Here’s an example of using lambda to filter even numbers:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
Output:
[2, 4, 6]
The lambda function checks if a number is even (x % 2 == 0), and filter() returns the elements where the lambda function returns True.
Example with sorted():
The sorted() function returns a sorted list from an iterable. You can use a lambda function to specify a custom sorting criterion.
points = [(2, 4), (1, 5), (4, 1)]
sorted_points = sorted(points, key=lambda point: point[1])
print(sorted_points)
Output:
[(4, 1), (2, 4), (1, 5)]
In this example, the lambda function specifies that the list should be sorted by the second element (index 1) of each tuple.
4. Lambda for Simple Functions
Lambda functions are useful when you need a simple function for a short period of time. For example, if you want to add 10 to each number in a list, you can use a lambda function:
numbers = [1, 2, 3, 4]
add_ten = lambda x: x + 10
new_numbers = list(map(add_ten, numbers))
print(new_numbers)
Output:
[11, 12, 13, 14]
5. Lambda in Sorting with key Argument
Lambda is often used to sort data with specific keys, such as sorting a list of dictionaries by a particular key.
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
sorted_people = sorted(people, key=lambda person: person["age"])
print(sorted_people)
Output:
[{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
In this case, the lambda function extracts the age key from each dictionary to sort the list of people by age.
6. Lambda for Conditional Expressions
You can use lambda functions with conditional expressions to perform simple conditional operations. Here’s an example of returning the larger of two numbers:
max_num = lambda a, b: a if a > b else b
print(max_num(10, 20))
Output:
20
This lambda function compares two numbers and returns the larger one.
7. Lambda with reduce()
The reduce() function from the functools module allows you to apply a function cumulatively to the items in an iterable. Here’s an example of using a lambda function to compute the product of all numbers in a list:
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
Output:
24
In this example, the lambda function is used to multiply all the elements in the list.
8. Limitations of Lambda Functions
- Single Expression: A lambda function can only contain a single expression. It cannot have multiple statements like a regular function.
- Readability: Lambda functions can be harder to understand for people unfamiliar with Python or functional programming.
9. Lambda vs. Regular Functions
Lambda functions are more concise than regular functions but are typically used for simple operations that do not require the additional overhead of a full function definition.
Regular function:
def add(x, y):
return x + y
Lambda function:
add = lambda x, y: x + y
The lambda function has no name, and it is used primarily for short, simple tasks. If the function becomes more complex, it is better to define a regular function for clarity.
Summary of Lambda Functions:
- Anonymous functions: Defined using the
lambdakeyword. - Concise: Useful for small, simple operations that can be written in one line.
- Arguments and Expression: Takes arguments and returns the result of a single expression.
- Common Uses: Frequently used with functions like
map(),filter(),sorted(),reduce(), and for simple sorting or filtering tasks. - Limitations: Cannot contain multiple statements or complex logic.