A lambda function in Python is a small, anonymous function defined using the lambda keyword.
- It has no name
- It can take any number of arguments
- It can contain only one expression
- It returns the result automatically
Lambda functions are often used when a function is needed for a short time and simple logic.
def square(x):
return x * xsquare = lambda x: x * xBoth produce the same result.
lambda arguments: expressionlambda→ keywordarguments→ inputs (like parameters)expression→ single expression whose result is returned
return keyword is used — it’s implicit.
square = lambda x: x * x
print(square(5))Output:
25
add = lambda a, b: a + b
print(add(3, 4))Output:
7
say_hello = lambda: "Hello!"
print(say_hello())Output:
Hello!
Since lambdas allow only one expression, conditional logic must be written using a ternary expression.
is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(10))
print(is_even(7))Output:
Even
Odd
def multiply(a, b):
return a * bmultiply = lambda a, b: a * b✅ Use lambda when:
- Logic is simple
- Function is short-lived
❌ Avoid lambda when:
- Logic is complex
- Multiple statements are required
Lambda functions shine when used with higher-order functions.
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, numbers))
print(squares)Output:
[1, 4, 9, 16]
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)Output:
[2, 4, 6]
points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda x: x[1])
print(sorted_points)Output:
[(5, 0), (3, 1), (1, 2)]
def apply_function(func, value):
return func(value)
print(apply_function(lambda x: x * 2, 10))Output:
20
##️ 8. Lambda and *args
sum_all = lambda *args: sum(args)
print(sum_all(1, 2, 3, 4))Output:
10
❌ Cannot contain multiple expressions
❌ Cannot have statements like print, for, while, try
❌ Cannot have assignments (=)
❌ Hard to debug when overused
| Mistake | Why It Happens |
|---|---|
| Writing complex logic | Lambda allows only one expression |
| Overusing lambdas | Reduces readability |
| Using for long functions | Lambdas are meant to be short |
| Expecting statements | Lambdas support expressions only |
| Debugging difficulty | No function name |
| Scenario | Use |
|---|---|
| One-line simple logic | Lambda |
| Reusable logic | def |
| Passed as argument | Lambda |
| Complex logic | def |
| Debugging needed | def |
| Feature | Lambda Function |
|---|---|
| Name | Anonymous |
| Lines | Single line |
| Return | Implicit |
| Statements | ❌ Not allowed |
| Best use | Short-lived functions |
- Create a lambda to check if a number is positive or negative.
- Use
map()with lambda to convert a list of temperatures from °C to °F. - Sort a list of dictionaries by a specific key using lambda.
- Rewrite a small
deffunction as a lambda. - Explain why lambda should not replace all functions.