Lambda Functions, map(), and filter()
Sometimes you need a short, throwaway function for a single calculation. Lambda functions provide compact inline definitions.
What is it?
A `lambda` function is a small, anonymous function that can take any number of arguments, but can only have one expression.
Why is it used?
Passed as quick callbacks to functions like `sorted(..., key=lambda x: ...)` and functional iterators.
Detailed Explanation
Syntax: `lambda arguments: expression`
No `def`, no function name, and no explicit `return` keyword—the single expression is evaluated and returned automatically.
Functional Built-ins:
• `map(func, iterable)`: Applies function to every element.
• `filter(func, iterable)`: Keeps items where function returns True.
Note: In modern Python, list comprehensions are often preferred over `map()` and `filter()` for readability.
Syntax Structure
Syntax Blueprint
square = lambda x: x ** 2
sorted_items = sorted(data, key=lambda item: item['price'])
Code Example
PYTHON Code
# Sorting Courses by Price using Lambda Key
courses = [
{"title": "Excel Mastery", "price": 1800},
{"title": "Advanced Python", "price": 2500},
{"title": "Full-Stack Web Dev", "price": 4500},
{"title": "C Programming", "price": 2000}
]
# Sort ascending by price using lambda
sorted_by_price = sorted(courses, key=lambda c: c["price"])
print("=== Courses Sorted by Price ===")
for c in sorted_by_price:
print(f"{c['title']:<22} : ₹{c['price']}")
# filter() with lambda: Courses under ₹2500
affordable = list(filter(lambda c: c["price"] <= 2000, courses))
print("\nAffordable Courses:", [c["title"] for c in affordable])
Explanation of the Code
• `key=lambda c: c["price"]` tells `sorted()` to compare dictionaries by their numeric price value.
• `filter(lambda ...)` filters for items under ₹2000.
Expected Output
=== Courses Sorted by Price ===
Excel Mastery : ₹1800
C Programming : ₹2000
Advanced Python : ₹2500
Full-Stack Web Dev : ₹4500
Affordable Courses: ['Excel Mastery', 'C Programming']
Real-World Application
Used across pandas dataframes (`df.apply(lambda row: ...)`), GUI event handlers, and data sorting algorithms.
Common Mistakes to Avoid
• Trying to write multiple statements or assignments inside a lambda (lambdas only support a single expression).
• Overusing lambdas where a named `def` function would be much clearer.
Quick Practice Challenge
Sort a list of strings `['Python', 'C', 'JavaScript', 'Go']` by string length using `sorted()` and a lambda.
Key Takeaways
• Lambdas are one-line anonymous functions: `lambda x: x * 2`.
• Primarily used as custom sort keys in `sorted()` and `min()`/`max()`.
• Prefer list comprehensions for general mapping and filtering.