Thuta Learning
AdvancedProgrammingbeginner

Lambda Functions (In Depth)

Relax. We'll talk through this in plain words — no textbook voice.

⚡ Lesson 62: Python Lambda Functions (Anonymous Functions)

1. What Is a Lambda Function?

In short → A lambda function is an anonymous function (a function with no name), and you can write it in a single line using the lambda keyword.

In detail → A lambda function is an anonymous function defined using the lambda keyword, usually written in a single line.

2. Lambda Syntax

lambda arguments: expression

In plain termsarguments are the parameters, and the expression is what gets returned.

3. Summary

✅ Lambda = anonymous function (no name)

✅ Syntax → lambda args: expression

✅ Common places to use it → 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
Lambda Functions (In Depth) | Thuta Learning