Lambda functions in Python are small, anonymous functions that can have any number of arguments but can only have one expression. They are also known as lambda expressions or anonymous functions.
The basic syntax of a lambda function is:
lambda arguments: expression
Lambda functions are typically used for short, simple operations where a full function definition would be verbose or unnecessary.
map()
, filter()
, and reduce()
# Lambda function to square a number
square = lambda x: x ** 2
print(square(5)) # Output: 25
In this example, we define a lambda function that squares its input. It's equivalent to:
def square(x):
return x ** 2
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(3, 4)) # Output: 7
Lambda functions are particularly useful in scenarios where you need a simple function for a short period. They're commonly used with built-in functions like sorted()
, map()
, and filter()
.
pairs = [(1, 'one'), (3, 'three'), (2, 'two'), (4, 'four')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[1])
print(sorted_pairs)
# Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
In this example, we use a lambda function as the key for sorting, based on the second element of each tuple.
While lambda functions are powerful, they have some limitations:
return
, assert
, or raise
)For more complex operations, consider using regular Python Functions instead.
Lambda functions in Python offer a concise way to create small, anonymous functions. They're particularly useful for simple operations and when working with higher-order functions. While they have limitations, understanding and using lambda functions can lead to more elegant and efficient code in appropriate situations.