Python - lambda function
In Python, a lambda function is a small, anonymous function that is defined using the lambda keyword. Unlike a standard function defined with def, a lambda function has no name and is typically used for short, simple operations that are intended to be used temporarily, such as within another function, or passed as an argument to higher-order functions like map, filter, and sorted.
In this post, we’ll cover:
Syntax of Lambda Functions
Basic Examples
Using Lambda with Built-in Functions
Common Use Cases
Syntax of Lambda Functions
The syntax for a lambda function is compact and easy to remember:
lambda arguments: expression
Arguments: A comma-separated list of inputs (similar to parameters in a standard function).
Expression: A single expression that’s evaluated and returned.
Example
A simple lambda function to add two numbers:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
This is functionally equivalent to:
def add(x, y):
return x + y
Basic Examples
Example 1: Lambda Function without a Name
A lambda function can be used without assigning it to a variable, which is useful in situations where you need a quick, one-time operation.
print((lambda x, y: x * y)(3, 4)) # Output: 12
Example 2: Lambda with One Argument
square = lambda x: x ** 2
print(square(5)) # Output: 25
Example 3: Lambda with Multiple Arguments
Lambda functions can take multiple arguments and handle operations like addition, concatenation, or conditionals.
concatenate = lambda a, b: a + " " + b
print(concatenate("Hello", "World")) # Output: "Hello World"
Using Lambda with Built-in Functions
Lambda functions are often used as arguments in higher-order functions like map, filter, and sorted to enable quick operations without defining separate functions.
1. map()
map() applies a function to each item in an iterable (like a list) and returns a new iterable.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
2. filter()
filter() is used to filter elements from an iterable that satisfy a condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
3. sorted()
sorted() can take a lambda function as a key to customize sorting.
points = [(1, 2), (3, 1), (5, -1), (2, 3)]
sorted_points = sorted(points, key=lambda point: point[1])
print(sorted_points) # Output: [(5, -1), (3, 1), (1, 2), (2, 3)]
In this example, the points are sorted based on their second element.
Common Use Cases for Lambda Functions
1. Simple Calculations
Lambda functions are a quick way to perform small calculations or manipulations without defining a new function.
calculate_percentage = lambda part, whole: (part / whole) * 100
print(calculate_percentage(25, 200)) # Output: 12.5
2. Using Lambda in Data Processing
Lambda functions are frequently used in data processing workflows, especially with libraries like pandas.
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Catherine'], 'age': [25, 30, 35]}
df = pd.DataFrame(data)
# Apply lambda to add 5 years to each person's age
df['age_plus_five'] = df['age'].apply(lambda x: x + 5)
print(df)
3. Conditional Expressions
Lambda functions can also be used with conditionals, though only single expressions are allowed.
max_value = lambda x, y: x if x > y else y
print(max_value(10, 20)) # Output: 20
4. Sorting Custom Objects
Lambda functions are commonly used to sort complex data structures, like a list of dictionaries.
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 72},
{"name": "Catherine", "grade": 90}
]
sorted_students = sorted(students, key=lambda student: student["grade"])
print(sorted_students)
In this example, the list of students is sorted by their grade in ascending order.
Advantages and Limitations of Lambda Functions
Advantages
Conciseness: Lambda functions provide a compact way to write simple functions.
Quick Usage: Useful for temporary, one-time operations like sorting, filtering, or mapping.
Anonymous: No need to assign a function name, making them ideal for inline functions.
Limitations
Single Expression: Lambda functions can only contain a single expression, limiting their complexity.
No Statements: Statements (like loops or multiple expressions) are not allowed within a lambda.
Readability: Excessive use of lambda functions can make code harder to read, so it’s best to use them for simple operations.