Introduction
Python lambda functions are anonymous functions defined inline without a name. They are particularly useful for short, simple operations that don't require a full function definition. Lambda functions are extensively used with higher-order functions like map, filter, and sorted, as well as in data science for creating quick transformation functions.
Key Concepts
- Anonymous functions: No formal name required
- Single expression: Lambda body must be a single expression
- Input parameters: Support multiple arguments
- Limitations: Cannot contain statements or multiple expressions
- Use cases: Sorting, mapping, filtering, key functions
- Closures: Can capture variables from enclosing scope
Python Implementation
# Basic lambda functions
square = lambda x: x ** 2
add = lambda a, b: a + b
greet = lambda name: f"Hello, {name}!"
# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# Lambda in sorted
pairs = [(1, "one"), (3, "three"), (2, "two")]
sorted_by_first = sorted(pairs, key=lambda x: x[0])
sorted_by_second = sorted(pairs, key=lambda x: x[1])
# Lambda with max/min
data = [{"name": "Alice", "score": 85}, {"name": "Bob", "score": 92}]
top_scorer = max(data, key=lambda x: x["score"])
# Lambda in comprehensions
result = [lambda x: x * 2 for i in range(3)] # List of functions
# Sorting DataFrame equivalent
import pandas as pd
df = pd.DataFrame({"A": [3, 1, 2], "B": ["a", "c", "b"]})
df_sorted = df.sort_values(by="A", key=lambda col: col * -1)
# Lambda with default arguments
multiply = lambda x, y=1: x * y
When to Use
- Simple one-off transformations
- Key functions for sorting
- Filtering data based on conditions
- Creating quick callback functions
- Functional programming patterns
- Short operations where full function is overkill
Key Takeaways
- Lambda functions are best for simple, short operations
- Avoid complex logic in lambdas; prefer regular functions for readability
- Lambdas are commonly used with map, filter, and sorted
- Lambda can capture variables from the enclosing scope (closure)
- Named lambdas (assigning to variable) defeats the purpose of anonymity