Python Lambda
A lambda function in Python is a small anonymous function defined using the lambda
keyword. It can take any number of arguments but can only have one expression.
1. Syntax
The basic syntax of a lambda function is:
lambda arguments: expression
2. Using Lambda Functions
Lambda functions are often used as a shortcut for simple functions where defining a full function using the def
keyword is unnecessary.
Example:
add = lambda x, y: x + y
print(add(3, 5))
3. Using Lambda with Built-in Functions
Lambda functions are commonly used with built-in functions like map()
, filter()
, and reduce()
.
Example:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
4. Limitations
While lambda functions are convenient for writing small, inline functions, they are limited to a single expression and cannot contain multiple statements or complex logic.
Conclusion
Lambda functions provide a concise way to define simple functions in Python. They are particularly useful in situations where you need a small anonymous function for a short period of time.