Lambda expressions are a concise way to create anonymous functions in Python. They allow you to define a function in a single line without formally declaring it using the def keyword. The syntax for a lambda function is:
lambda arguments: expression
Key Features of Lambda Expressions:
- Anonymous: Lambda functions do not have a name.
- Single Expression: They can only contain a single expression, which is evaluated and returned.
- Use Cases: Commonly used for short functions that are passed as arguments to higher-order functions like
map(),filter(), andsort().
Example Usage:
-
Sorting a List:
You can use a lambda function to sort a list of objects based on a specific attribute.portfolio.sort(key=lambda s: s.shares) -
Mathematical Operations:
You can define simple mathematical operations using lambda.multiply = lambda x, y: x * y result = multiply(2, 3) # result will be 6 -
In DataFrames:
You can use lambda functions to create new columns in a DataFrame.df = df.assign(E=lambda x: x['A'] + 1)
Lambda functions are particularly useful for short, throwaway functions that are not reused elsewhere in your code.
