► Understanding Lambda Functions
Lambda functions are small, anonymous functions defined in a single line. They can have any number of parameters but only one expression. Lambda functions are useful for short, simple operations that you need temporarily.
► Real-World Analogy
Think of lambda functions like sticky notes with quick instructions:
» A full function is like a detailed instruction manual with a title and multiple steps
» A lambda function is like a quick note: “Add 5” or “Multiply by 2”
» You use sticky notes for simple, one-time reminders
» You don’t need to give them formal names
» Perfect for quick tasks you won’t reuse elsewhere
► Key Concepts
✓ Anonymous functions: No name required
✓ Single expression: Can only contain one expression
✓ Inline definition: Defined where they’re used
✓ Return implicit: Automatically returns expression result
✓ Common with map(), filter(), sort(): Often used as arguments
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Basic lambda function add = lambda x, y: x + y print(add(5, 3)) # Lambda vs regular function # Regular function def square(x): return x ** 2 # Lambda equivalent square_lambda = lambda x: x ** 2 print(square_lambda(4)) # Lambda with map() numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, numbers)) print(f"Squared: {squared}") # Lambda with filter() even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(f"Even numbers: {even_numbers}") # Lambda with sorted() students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)] sorted_students = sorted(students, key=lambda x: x[1], reverse=True) print(f"Sorted by grade: {sorted_students}") |
