Topic 11: Lambda Functions
In Python, a Lambda Function is a small, anonymous function. It is "anonymous" because it doesn't have a name like a standard function defined with the def keyword.
Think of it as a "disposable" one-liner used for simple tasks.
1. The Syntax
The syntax is very specific: lambda arguments : expression
It can take any number of arguments.
It can only have one expression.
The result of that expression is automatically returned.
2. Why use them?
You use lambda functions when you need a function for a short period, often as an argument inside higher-order functions like map(), filter(), or sort().
# --- Example 1: Basic Math ---
# A lambda that adds 10 to a number
add_ten = lambda x : x + 10
print(add_ten(5)) # Output: 15
# --- Example 2: Multiple Arguments ---
multiply = lambda a, b : a * b
print(multiply(4, 5)) # Output: 20
# --- Example 3: Using with sorting ---
# Sorting a list of tuples by the second item (the age)
people = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
people.sort(key=lambda person: person[1])
print(people) # Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]