Lambda Functions
Introduction to Lambda Functions
Lambda functions are small, anonymous functions defined with the lambda keyword. They can have any number of arguments but only one expression. Lambda functions are useful for short, simple operations, especially when passed as arguments to other functions.
Lambda functions are often used with functions like map(), filter(), and sorted().
Basic Lambda Syntax
The syntax is: lambda arguments: expression
lambda_basic.py
# Regular function
def add(x, y):
return x + y
# Lambda equivalent
add_lambda = lambda x, y: x + y
print(add(5, 3)) # 8
print(add_lambda(5, 3)) # 8
# Single argument
square = lambda x: x ** 2
print(square(5)) # 25
# No arguments
greet = lambda: "Hello, World!"
print(greet()) # Hello, World!
Using Lambda with Built-in Functions
Lambda functions are commonly used with map(), filter(), and sorted():
lambda_builtin.py
# map() - apply function to all items
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16]
# filter() - filter items based on condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
# sorted() - custom sorting
people = [("Alice", 25), ("Bob", 30), ("Charlie", 20)]
sorted_by_age = sorted(people, key=lambda x: x[1])
print(sorted_by_age) # [('Charlie', 20), ('Alice', 25), ('Bob', 30)]
# Multiple arguments
add = lambda x, y, z: x + y + z
print(add(1, 2, 3)) # 6
Lambda vs Regular Functions
When to use lambda functions:
lambda_vs_def.py
# Use lambda for simple, one-line functions
# Especially when used once or passed as argument
# Good use of lambda
numbers = [1, 2, 3, 4]
result = list(map(lambda x: x * 2, numbers))
# For complex logic, use regular function
def complex_calculation(x):
# Multiple lines of logic
if x > 10:
return x * 2
else:
return x + 5
# This is better as a regular function
Best Practices
✅ Lambda Function Tips
• Use lambda for simple, one-expression functions
• Great for functions used once or passed as arguments
• Use regular functions for complex logic
• Lambda functions can't contain statements (only expressions)
• Keep lambda functions readable
main.py
📤 Output
Click "Run" to execute...