Anonymous Functions (Lambda) in Python
Lambda functions are small, anonymous functions created with the lambda keyword. They're useful for short operations, especially with functions like map(), filter(), and sorted().
Contents
Basic lambda syntax
Lambda functions are defined with lambda followed by parameters and an expression.
square = lambda x: x ** 2
print(square(5))
>>> 25
Lambda functions can take multiple arguments.
add = lambda x, y: x + y
print(add(3, 7))
>>> 10
They can also take no arguments.
get_answer = lambda: 42
print(get_answer())
>>> 42
Lambda with map()
map() applies a function to every item in an iterable. Lambda works well here for simple transformations.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
>>> [1, 4, 9, 16, 25]
You can use lambda with multiple iterables in map().
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
sums = list(map(lambda x, y: x + y, numbers1, numbers2))
print(sums)
>>> [5, 7, 9]
Lambda with filter()
filter() returns items from an iterable where a function returns True. Lambda is ideal for simple conditions.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
>>> [2, 4, 6, 8, 10]
You can combine multiple conditions in lambda.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = list(filter(lambda x: x % 2 == 0 and x > 5, numbers))
print(filtered)
>>> [6, 8, 10]
Lambda with sorted()
sorted() accepts a key parameter for custom sorting. Lambda is perfect for extracting sort keys.
students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
sorted_by_age = sorted(students, key=lambda x: x[1])
print(sorted_by_age)
>>> [('Bob', 20), ('Charlie', 22), ('Alice', 25)]
You can sort by multiple criteria using tuples in the key function.
students = [("Alice", 25, "A"), ("Bob", 25, "B"), ("Charlie", 20, "A")]
sorted_students = sorted(students, key=lambda x: (x[1], x[2]))
print(sorted_students)
>>> [('Charlie', 20, 'A'), ('Alice', 25, 'A'), ('Bob', 25, 'B')]
Lambda works with dictionaries too.
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 20},
{"name": "Charlie", "age": 22}
]
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
>>> [{'name': 'Bob', 'age': 20}, {'name': 'Charlie', 'age': 22}, {'name': 'Alice', 'age': 25}]
Lambda with reduce()
reduce() applies a function cumulatively to items. Lambda is useful for simple reductions.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)
>>> 120
You can provide an initial value to reduce().
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_with_initial = reduce(lambda x, y: x + y, numbers, 10)
print(sum_with_initial)
>>> 25
Lambda limitations
Lambda functions are limited to a single expression. They can't contain statements like print(), return, or if-else blocks in the traditional sense.
# This works: conditional expression
max_value = lambda x, y: x if x > y else y
print(max_value(5, 3))
>>> 5
# This doesn't work: multiple statements
# invalid = lambda x: print(x); return x * 2
For complex logic, use a regular function instead.
# Instead of trying to force complex logic into lambda
def process_number(x):
if x < 0:
return 0
elif x > 100:
return 100
return x
# Use the regular function
numbers = [-5, 50, 150]
processed = list(map(process_number, numbers))
print(processed)
>>> [0, 50, 100]
When to use lambda
Use lambda for short, simple operations that are used once, especially with higher-order functions.
# Good use: simple transformation
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
>>> [2, 4, 6, 8, 10]
# Good use: simple filtering
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
>>> [2, 4]
# Good use: simple sorting
words = ["apple", "banana", "cherry"]
sorted_by_length = sorted(words, key=lambda x: len(x))
print(sorted_by_length)
>>> ['apple', 'cherry', 'banana']
Avoid lambda for complex logic or when you need to reuse the function.
# Instead of this:
# complex_lambda = lambda x: [complicated logic here]
# Use a named function:
def complex_operation(x):
# Multiple lines of logic
result = x * 2
if result > 10:
result += 5
return result
numbers = [3, 5, 7]
processed = list(map(complex_operation, numbers))
print(processed)
>>> [11, 15, 19]