A lambda function is a small, anonymous function in Python that is designed to perform a simple operation.
Unlike a normal function created using def, a lambda function does not require a function name or a return statement.
Normal Function
def square(x):
return x * x
print(square(5))Lambda Function
square = lambda x: x * x
print(square(5))Both produce:
25Lambda functions are useful when the logic is short, simple, and needed for a small task.
Basic Syntax
lambda arguments: expressionFor example:
lambda x: x * 2Here:
lambda→ keyword used to create the lambda functionx→ parameterx * 2→ expression whose result is returned automatically
1. Creating a Simple Lambda Function
square = lambda x: x * x
print(square(5))Output:
25The lambda function:
lambda x: x * xtakes a number and returns its square.
2. Lambda with One Parameter
A lambda function can accept one parameter.
double = lambda x: x * 2
print(double(10))
print(double(25))Output:
20
50Another example:
cube = lambda x: x * x * x
print(cube(3))Output:
273. Lambda with Multiple Parameters
A lambda function can accept multiple parameters.
add = lambda a, b: a + b
print(add(10, 20))Output:
30Another example:
multiply = lambda a, b: a * b
print(multiply(5, 6))Output:
304. Lambda with Three Parameters
calculate = lambda a, b, c: a + b + c
print(calculate(10, 20, 30))Output:
60The number of parameters is not fixed.
lambda a: ...
lambda a, b: ...
lambda a, b, c: ...5. Lambda with No Parameter
A lambda function can also have no parameters.
message = lambda: "Welcome to Python Bootcamp"
print(message())Output:
Welcome to Python BootcampNotice that the function is called using:
message()because it doesn't require any arguments.
6. Lambda Automatically Returns the Result
With a normal function, we usually use return.
def add(a, b):
return a + bWith lambda, the expression is automatically returned.
add = lambda a, b: a + bSo we don't write:
lambda a, b: return a + bThis is incorrect.
The correct syntax is:
lambda a, b: a + b7. Lambda with Strings
Lambda functions can also work with strings.
get_length = lambda text: len(text)
print(get_length("Python"))
print(get_length("SkillMantra"))Output:
6
11Another example:
uppercase = lambda text: text.upper()
print(uppercase("python bootcamp"))Output:
PYTHON BOOTCAMP8. Lambda with String Concatenation
full_name = lambda first, last: first + " " + last
print(full_name("Rajendra", "Kandel"))Output:
Rajendra Kandel9. Lambda with Conditional Expression
Lambda can contain a conditional expression.
check = lambda x: "Positive" if x > 0 else "Negative"
print(check(10))
print(check(-5))Output:
Positive
NegativeAnother example:
check_age = lambda age: "Adult" if age >= 18 else "Minor"
print(check_age(25))
print(check_age(15))Output:
Adult
Minor10. Lambda for Even and Odd
check_number = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_number(10))
print(check_number(7))Output:
Even
Odd11. Lambda with Default Arguments
Lambda functions can have default values.
greet = lambda name="Student": "Hello " + name
print(greet())
print(greet("Raj"))Output:
Hello Student
Hello RajThe default value is used when no argument is provided.
12. Lambda with Multiple Default Arguments
calculate = lambda a=10, b=20: a + b
print(calculate())
print(calculate(50, 100))Output:
30
15013. Lambda Can Be Stored in a Variable
Although lambda functions are anonymous, we can assign them to variables.
greet = lambda: "Hello Python"
print(greet())Here:
greetholds a reference to the lambda function.
14. Multiple Lambda Functions
We can create several lambda functions.
add = lambda a, b: a + b subtract = lambda a, b: a - b multiply = lambda a, b: a * b
print(add(20, 10))
print(subtract(20, 10))
print(multiply(20, 10))Output:
30
10
20015. Lambda vs Normal Function
Normal Function
def square(number):
return number * number
print(square(5))Lambda Function
square = lambda number: number * number
print(square(5))Both return:
25Main Difference
| Normal Function | Lambda Function |
|---|---|
Uses def | Uses lambda |
| Usually has a name | Anonymous by design |
| Can contain multiple statements | Designed for one expression |
Uses return | Result is returned automatically |
| Better for complex logic | Better for simple logic |
16. Lambda with Function as an Argument
A lambda function itself can be passed to another function.
This is an important concept, but we are not covering map(), filter(), or other functions here.
Example:
def calculate(number, operation):
return operation(number)
result = calculate(
5,
lambda x: x * x
)
print(result)Output:
25Here:
lambda x: x * xis passed into the calculate() function.
Another example:
result = calculate(
10,
lambda x: x + 100
)
print(result)Output:
11017. Returning a Lambda from a Function
A normal function can return a lambda function.
def create_multiplier(number):
return lambda x: x * number
double = create_multiplier(2)
print(double(10))
print(double(20))Output:
20
40Another example:
triple = create_multiplier(3)
print(triple(10))Output:
30This is a useful example of how Python functions can work with other functions.
18. Practical Example : Calculate Discount
discount = lambda price: price - (price * 0.10)
print(discount(1000))
print(discount(5000))Output:
900.0
4500.0The lambda applies a 10% discount.
19. Practical Example : Calculate Tax
calculate_tax = lambda price: price * 0.13
print(calculate_tax(1000))Output:
130.020. Practical Example : Calculate Final Price
final_price = lambda price, discount: price - (price * discount / 100)
print(final_price(1000, 10))
print(final_price(5000, 20))Output:
900.0
4000.021. Practical Example : Student Result
result = lambda marks: "Pass" if marks >= 40 else "Fail"
print(result(75))
print(result(35))Output:
Pass
Fail22. Practical Example : Grade Calculator
grade = lambda marks: (
"A+" if marks >= 80
else "A" if marks >= 70
else "B+" if marks >= 60
else "B" if marks >= 50
else "Fail"
)
print(grade(85))
print(grade(72))
print(grade(45))Output:
A+
A
FailFor complicated grading logic, however, a normal function is generally easier to read.
23. Lambda with Boolean Results
A lambda can directly return True or False.
is_adult = lambda age: age >= 18
print(is_adult(25))
print(is_adult(15))Output:
True
FalseAnother example:
is_even = lambda number: number % 2 == 0
print(is_even(10))
print(is_even(7))24. Lambda with Mathematical Expressions
area = lambda length, width: length * width
print(area(10, 5))Output:
50Circle area:
circle_area = lambda radius: 3.14159 * radius * radius
print(circle_area(5))25. When Should We Use Lambda?
Lambda functions are useful when:
- The operation is very short.
- The function is needed only for a small task.
- The logic can be expressed clearly in one expression.
- We want to pass a small function to another function.
- Creating a full
deffunction would add unnecessary code.
Example:
square = lambda x: x * xThis is a good use of lambda because the logic is simple and immediately understandable.
26. When Should We Avoid Lambda?
Don't use lambda when the logic becomes complicated.
For example, instead of creating a very long lambda:
result = lambda x: ...use:
def calculate_result(x):
# complex logic here
return resultA good rule for students:
If a lambda is difficult to read, use
definstead.
Readable code is more important than writing fewer lines.
27. Important Rules of Lambda Functions
Remember these rules:
Rule 1 : Use the lambda keyword
lambda x: x * 2Rule 2 : Parameters come before :
lambda x, y: x + yRule 3 : The expression comes after :
lambda x: x * xRule 4 : The result is automatically returned
square = lambda x: x * xRule 5 : Lambda is intended for simple expressions
Don't use it to write complicated business logic.
Copy Code
# ========================================== # Python Lambda Functions # ==========================================
# ------------------------------------------ # 1. Basic lambda function # ------------------------------------------
square = lambda x: x * x
print(square(5))
# ------------------------------------------ # 2. Lambda with one parameter # ------------------------------------------
double = lambda x: x * 2
print(double(10))
print(double(25))
# ------------------------------------------ # 3. Lambda with multiple parameters # ------------------------------------------
add = lambda a, b: a + b
print(add(10, 20))
# ------------------------------------------ # 4. Lambda with three parameters # ------------------------------------------
calculate = lambda a, b, c: a + b + c
print(calculate(10, 20, 30))
# ------------------------------------------ # 5. Lambda without parameters # ------------------------------------------
message = lambda: "Welcome to Python Bootcamp"
print(message())
# ------------------------------------------ # 6. Lambda with strings # ------------------------------------------
get_length = lambda text: len(text)
print(get_length("Python"))
print(get_length("SkillMantra"))
# ------------------------------------------ # 7. Convert string to uppercase # ------------------------------------------
uppercase = lambda text: text.upper()
print(uppercase("python bootcamp"))
# ------------------------------------------ # 8. String concatenation # ------------------------------------------
full_name = lambda first, last: first + " " + last
print(full_name("Rajendra", "Kandel"))
# ------------------------------------------ # 9. Lambda with condition # ------------------------------------------
check_age = lambda age: "Adult" if age >= 18 else "Minor"
print(check_age(25))
print(check_age(15))
# ------------------------------------------ # 10. Even or Odd # ------------------------------------------
check_number = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_number(10))
print(check_number(7))
# ------------------------------------------ # 11. Default argument # ------------------------------------------
greet = lambda name="Student": "Hello " + name
print(greet())
print(greet("Raj"))
# ------------------------------------------ # 12. Multiple default arguments # ------------------------------------------
calculate = lambda a=10, b=20: a + b
print(calculate())
print(calculate(50, 100))
# ------------------------------------------ # 13. Multiple lambda functions # ------------------------------------------
add = lambda a, b: a + b subtract = lambda a, b: a - b multiply = lambda a, b: a * b divide = lambda a, b: a / b
print(add(20, 10))
print(subtract(20, 10))
print(multiply(20, 10))
print(divide(20, 10))
# ------------------------------------------ # 14. Lambda with Boolean result # ------------------------------------------
is_adult = lambda age: age >= 18
print(is_adult(25))
print(is_adult(15))
# ------------------------------------------ # 15. Check even number # ------------------------------------------
is_even = lambda number: number % 2 == 0
print(is_even(10))
print(is_even(7))
# ------------------------------------------ # 16. Discount calculation # ------------------------------------------
discount = lambda price: price - (price * 0.10)
print(discount(1000))
print(discount(5000))
# ------------------------------------------ # 17. Tax calculation # ------------------------------------------
calculate_tax = lambda price: price * 0.13
print(calculate_tax(1000))
# ------------------------------------------ # 18. Final price calculation # ------------------------------------------
final_price = lambda price, discount: (
price - (price * discount / 100)
)
print(final_price(1000, 10))
print(final_price(5000, 20))
# ------------------------------------------ # 19. Student result # ------------------------------------------
result = lambda marks: "Pass" if marks >= 40 else "Fail"
print(result(75))
print(result(35))
# ------------------------------------------ # 20. Grade calculator # ------------------------------------------
grade = lambda marks: (
"A+" if marks >= 80
else "A" if marks >= 70
else "B+" if marks >= 60
else "B" if marks >= 50
else "Fail"
)
print(grade(85))
print(grade(72))
print(grade(45))
# ------------------------------------------ # 21. Mathematical calculation # ------------------------------------------
area = lambda length, width: length * width
print(area(10, 5))
# ------------------------------------------ # 22. Lambda as a function argument # ------------------------------------------
def calculate_number(number, operation):
return operation(number)
result = calculate_number(
5,
lambda x: x * x
)
print(result)
# ------------------------------------------ # 23. Returning lambda from a function # ------------------------------------------
def create_multiplier(number):
return lambda x: x * number
double = create_multiplier(2)
print(double(10))
print(double(20))
triple = create_multiplier(3)
print(triple(10))