Lambda Functions
Lambda functions, also known as anonymous functions, are small, one-time use functions that don't require a formal def statement. They are useful for short operations that are not going to be reused.
The basic syntax of a lambda function is:
lambda arguments: expression
Let's create a lambda function that adds 10 to a given number:
add_ten = lambda x: x + 10
print(add_ten(5)) # Output: 15
Lambda functions can take multiple arguments:
multiply = lambda x, y: x * y
print(multiply(3, 4)) # Output: 12
Lambda functions are often used with built-in functions like map(), filter(), and reduce():
# Using lambda with map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
# Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Lambda functions are often used as key functions in sorting operations:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
While lambda functions are convenient, they have some limitations:
Lambda functions are best used in situations where:
While lambda functions can make code more concise, it's important to balance brevity with readability. For more complex operations, it's often better to use a regular defined function.