Python Lambda Functions
Lambda Function Basics
Lambda functions are small, anonymous functions defined with the `lambda` keyword. They can take any number of arguments but contain only a single expression, whose result is automatically returned.
Example
# Basic lambda functions
# Regular function
def square(x):
return x * x
# Equivalent lambda function
square_lambda = lambda x: x * x
print(f"Square of 5: {square(5)}")
print(f"Square of 5 (lambda): {square_lambda(5)}")
# Lambda with multiple arguments
multiply = lambda x, y: x * y
print(f"3 * 4 = {multiply(3, 4)}")
Output
Square of 5: 25 Square of 5 (lambda): 25 3 * 4 = 12
Using Lambda with Built-in Functions
Lambda functions are often combined with built-in functions like `map()`, `filter()`, and `sorted()` to perform inline transformations.
Example
# Using lambda with map(), filter(), and sorted()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# map() with lambda: square all numbers
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared numbers: {squared}")
# filter() with lambda: get even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers: {evens}")
# sorted() with lambda: sort by last digit
numbers_to_sort = [23, 45, 12, 67, 89, 34]
sorted_by_last = sorted(numbers_to_sort, key=lambda x: x % 10)
print(f"Sorted by last digit: {sorted_by_last}")
Output
Squared numbers: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Even numbers: [2, 4, 6, 8, 10] Sorted by last digit: [12, 23, 34, 45, 67, 89]
Lambda in Higher-Order Functions
Lambda functions are useful in higher-order functions (functions that accept other functions as arguments).
Example
# Lambda in higher-order functions
# Function that returns a function
def make_multiplier(n):
return lambda x: x * n
double = make_multiplier(2)
triple = make_multiplier(3)
print(f"Double of 5: {double(5)}")
print(f"Triple of 5: {triple(5)}")
# Using lambda with reduce()
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(f"Product of numbers: {product}")
Output
Double of 5: 10 Triple of 5: 15 Product of numbers: 120
Practical Examples
Lambda functions are best suited for short, simple operations where defining a named function would be unnecessary.
Example
# Practical lambda examples
# Sorting list of tuples by second element
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[1])
print(f"Sorted by name: {sorted_pairs}")
# Simple validation with lambda
is_positive = lambda x: x > 0
numbers = [-2, 5, -1, 0, 3]
positive_numbers = list(filter(is_positive, numbers))
print(f"Positive numbers: {positive_numbers}")
# Simple inline action (conceptual example)
on_click = lambda: print("Button clicked!")
on_click()
Output
Sorted by name: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] Positive numbers: [5, 3] Button clicked!