⚡ Lesson 62: Python Lambda Functions (Anonymous Functions)
1. What Is a Lambda Function?
In short → A lambda function is an unnamed function (anonymous function) that you can write in a single line using the lambda keyword.
In other words → A lambda function is an anonymous function defined using the lambda keyword, usually written in a single line.
2. Lambda Syntax
lambda arguments: expression
Explained → arguments are the parameters, and expression is the return value.
3. Summary
✅ Lambda = anonymous function (no name)
✅ Syntax → lambda args: expression
✅ Commonly used with → map(), filter(), sorted()
✅ Great for short, one-time-use functions
python
# ===== 1. Basic Lambda =====
add = lambda x, y: x + y
print(f"add(5, 3) = {add(5, 3)}")
# ===== 2. Lambda vs Normal Function =====
print(f"\n===== Comparison =====")
def square(x):
return x**2
square_lambda = lambda x: x**2
print(f"square(4) = {square(4)}")
print(f"square_lambda(4) = {square_lambda(4)}")
# ===== 3. Lambda with map() =====
print(f"\n===== Lambda with map() =====")
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(f"Squares: {squares}")
# ===== 4. Lambda with filter() =====
print(f"\n===== Lambda with filter() =====")
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(f"Even numbers: {evens}")
# ===== 5. Lambda with sorted() =====
print(f"\n===== Lambda with sorted() =====")
data = [("Sai", 25), ("Aye", 20), ("Mya", 30)]
sorted_data = sorted(data, key=lambda x: x[1])
print(f"Sorted by age: {sorted_data}")
# ===== 6. Lambda with reduce() =====
print(f"\n===== Lambda with reduce() =====")
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(f"Product: {product}")You should see
add(5, 3) = 8 ===== Comparison ===== square(4) = 16 square_lambda(4) = 16 ===== Lambda with map() ===== Squares: [1, 4, 9, 16, 25] ===== Lambda with filter() ===== Even numbers: [2, 4, 6] ===== Lambda with sorted() ===== Sorted by age: [('Aye', 20), ('Sai', 25), ('Mya', 30)] ===== Lambda with reduce() ===== Product: 24