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