Spex3
    

Lambda Functions in Python (Anonymous Functions) πŸš€


    

    

A lambda function is a small, anonymous function that can have any number of arguments but only one expression.

βœ… Useful for short, throwaway functions
βœ… More concise than regular def functions
βœ… Often used with functions like map(), filter(), and sorted()

1️⃣ Syntax of a Lambda Function

πŸ“Œ Syntax:


lambda arguments: expression

πŸ“Œ Example:


square = lambda x: x * x
print(square(5)) # Output: 25

πŸ”Ή The function takes x as an argument and returns x * x.

2️⃣ Lambda vs. Regular Function

πŸ“Œ Regular function using def:


def add(a, b):
return a + b

print(add(3, 5)) # Output: 8

πŸ“Œ Same function using lambda:


add = lambda a, b: a + b
print(add(3, 5)) # Output: 8

πŸš€ Lambda is more concise but limited to one expression.

3️⃣ Using Lambda with map(), filter(), and sorted()

πŸ”Ή map() – Apply a Function to Each Element

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
πŸ”Ή filter() – Keep Elements That Meet a Condition

numbers = [10, 15, 20, 25, 30]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [10, 20, 30]

πŸ”Ή sorted() – Custom Sorting

students = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]
students_sorted = sorted(students, key=lambda x: x[1]) # Sort by age
print(students_sorted)
# Output: [('Bob', 20), ('Charlie', 23), ('Alice', 25)]

4️⃣ Lambda with if-else (Ternary Condition)

max_value = lambda a, b: a if a > b else b
print(max_value(10, 20)) # Output: 20

5️⃣ When to Use Lambda Functions?

βœ… When you need a short, one-time-use function

βœ… When passing a function as an argument (e.g., map(), filter())

βœ… When writing concise code

🚨 Avoid using lambda for complex logicβ€”use def instead for readability!


    Date: 2025-03-22 00:00:00.000000