Lambda functions are small, anonymous (unnamed) functions defined with the
lambda keyword. They can take any number of arguments but can only have one expression.🔹 1. What is a Lambda Function?
A compact way to write simple functions without
def. They are essentially a shortcut for defining simple, inline functions.Syntax:
lambda arguments: expression
Example:python
add_ten = lambda x: x + 10
print(add_ten(5))
Output:
15🔹 2. Why Use Lambda?
• Conciseness: Shorter syntax for simple operations.
• Anonymity: No need to name a function that will only be used once.
• Readability: Can make code cleaner when used appropriately in specific contexts.
🔹 3. Lambda with Multiple Arguments
Lambdas can take multiple arguments, just like regular functions.
Example:
multiply = lambda a, b: a × b
print(multiply(4, 7))
Output:
28🔹 4. Common Use Case 1:
filter()The
filter() function constructs an iterator from elements of an iterable for which a function returns True. Lambdas are often used as this function.Example:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output:
[2, 4, 6]🔹 5. Common Use Case 2:
map()The
map() function applies a given function to each item of an iterable and returns an iterator of the results.Example:
numbers = [1, 2, 3]
squared_numbers = list(map(lambda x: x × x, numbers))
print(squared_numbers)
Output:
[1, 4, 9]🔹 6. Common Use Case 3:
sorted() (Custom Sort Key)Lambdas are frequently used with
sorted() as the key argument to define custom sorting logic.Example:
students = [('Alice', 25), ('Bob', 20), ('Charlie', 30)]
# Sort by age (the second element of each tuple)
sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students)
Output:
[('Bob', 20), ('Alice', 25), ('Charlie', 30)]🎯 Today's Goal
✔️ Understand what lambda functions are
✔️ Write short, single-expression functions
✔️ Use lambdas effectively with
filter(), map(), and sorted()