5.6 The lambda function (BT101CO)
In Python, a Lambda Function is a small, anonymous function that is defined without a name using the lambda keyword. Unlike standard functions defined with def, lambdas are restricted to a single expression.
1. Syntax of a Lambda Function
The structure of a lambda function is very concise:
lambda arguments : expression
lambda: The keyword that initiates the function.- Arguments: One or more inputs (separated by commas).
- Colon (
:): Separates the arguments from the logic. - Expression: The single line of code that is executed and automatically returned.
2. Basic Example: Standard vs. Lambda
Let's compare a standard function with a lambda function that calculates the square of a number.
def square(x):
return x * x
print(square(5)) # 25
square_lambda = lambda x: x * x
print(square_lambda(5)) # 25
3. Key Characteristics
- Anonymous: They don't have a name unless you assign them to a variable.
- Single Expression: You cannot have multiple lines, loops, or complex
if-elseblocks. - Implicit Return: You don't type the word
return; the result of the expression is returned by default.
4. Advanced "Problem Solving" Uses
The true power of lambda functions is revealed when they are used as arguments inside higher-order functions.
A. Using with filter()
filter() keeps only items where the function returns True.
nums = [1, 2, 3, 4, 5, 6]
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]
B. Using with map()
map() applies the function to every item in a list.
nums = [1, 2, 3, 4]
# Double every number
doubled = list(map(lambda x: x * 2, nums))
print(doubled) # Output: [2, 4, 6, 8]
C. Using with sorted()
You can use a lambda as a "key" to sort complex data structures (like tuples).
students = [("Ashok", 85), ("Amit", 92), ("Suman", 78)]
# Sort by grade (the second element in the tuple)
students.sort(key=lambda x: x[1])
print(students) # Output: [('Suman', 78), ('Ashok', 85), ('Amit', 92)]
Summary Table
| Feature | def Function |
lambda Function |
|---|---|---|
| Keyword | def | lambda |
| Name | Required | Anonymous |
| Body | Multiple lines allowed | Single expression only |
| Return | Explicit return | Implicit return |
Lambda functions are like disposable tools—great for quick tasks inside other functions, but not intended for building entire systems.