What is Lambda Function in Python: Simple Explanation and Examples
lambda function in Python is a small, anonymous function defined with the lambda keyword. It can take any number of arguments but has only one expression, which is returned automatically.How It Works
Think of a lambda function as a quick, one-line recipe that you write on a sticky note instead of a full cookbook recipe. It lets you create a simple function without giving it a name. This is useful when you need a small function just once or in a short place.
Normally, functions have a name and a block of code. But a lambda function is like a mini-function that fits in one line and returns the result of its single expression automatically. You give it inputs, and it quickly gives you the output.
Example
This example shows a lambda function that adds two numbers. It takes two inputs and returns their sum.
add = lambda x, y: x + y result = add(3, 5) print(result)
When to Use
Use lambda functions when you need a simple function for a short time, especially as an argument to other functions like map, filter, or sorted. They help keep your code short and clean without defining a full function.
For example, if you want to sort a list of names by their length, a lambda function can quickly tell the sorting function how to compare them.
Key Points
- Anonymous: No need to name the function.
- Single expression: Only one line of code that returns a value.
- Useful for short tasks: Ideal for quick, simple functions.
- Common in functional programming: Works well with functions like
map,filter, andsorted.