Python Lambda
Learn about lambda functions in Python - small anonymous functions that can have any number of arguments.
Lambda Functions
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression The expression is executed and the result is returned:
Example - Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5)) Lambda functions can take any number of arguments:
Example - Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6)) Example - Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2)) Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
Example
def myfunc(n):
return lambda a : a * n Use that function definition to make a function that always doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11)) Or, use the same function definition to make a function that always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11)) Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11)) Use lambda functions when an anonymous function is required for a short period of time.
Lambda with Built-in Functions
Using Lambda with map()
The map() function applies a function to every item in an iterable:
Example
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25] Using Lambda with filter()
The filter() function filters items from an iterable based on a condition:
Example
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10] Using Lambda with reduce()
The reduce() function applies a function cumulatively to items in an iterable:
Example
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120 (1*2*3*4*5) Using Lambda with sorted()
Lambda functions are useful for custom sorting:
Example
students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
# Sort by grade (second element)
sorted_by_grade = sorted(students, key=lambda x: x[1])
print(sorted_by_grade)
# Sort by name length
sorted_by_name_length = sorted(students, key=lambda x: len(x[0]))
print(sorted_by_name_length) Practical Examples
Temperature Conversion
# Convert Celsius to Fahrenheit
celsius_to_fahrenheit = lambda c: (c * 9/5) + 32
temperatures_c = [0, 20, 30, 100]
temperatures_f = list(map(celsius_to_fahrenheit, temperatures_c))
print(temperatures_f) # [32.0, 68.0, 86.0, 212.0] String Processing
words = ["python", "lambda", "function", "programming"]
# Capitalize all words
capitalized = list(map(lambda x: x.capitalize(), words))
print(capitalized)
# Filter words longer than 6 characters
long_words = list(filter(lambda x: len(x) > 6, words))
print(long_words) Mathematical Operations
# Create a list of mathematical operations
operations = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y,
'multiply': lambda x, y: x * y,
'divide': lambda x, y: x / y if y != 0 else 'Cannot divide by zero'
}
print(operations['add'](10, 5)) # 15
print(operations['multiply'](4, 3)) # 12 Conditional Lambda
# Lambda with conditional expression
max_value = lambda a, b: a if a > b else b
print(max_value(10, 20)) # 20
# Check if number is even or odd
check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(7)) # Odd
print(check_even(8)) # Even Lambda vs Regular Functions
Lambda Functions
- Anonymous (no name)
- Single expression only
- Automatically return the result
- Good for simple operations
- Often used with map(), filter(), reduce()
# Lambda function
square = lambda x: x**2 Regular Functions
- Named functions
- Multiple statements allowed
- Explicit return statement needed
- Good for complex operations
- More readable for complex logic
# Regular function
def square(x):
return x**2 Best Practices
- Use lambda for simple, one-line functions
- Prefer regular functions for complex logic
- Lambda functions are great with functional programming concepts
- Don't assign lambda to variables; use def instead
- Use lambda when you need a function for a short period