🌱 Junior Track 21 of 21

21. Lambda Functions

Write lightweight, single-expression anonymous functions: master inline key callbacks for `sorted()`, `filter()`, and `map()`, while adhering to PEP 8 guidelines to avoid overusing lambda when `def` is clearer.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 21 — LAMBDA FUNCTIONS & HIGHER-ORDER FUNCTIONS
# ==============================================================================

# 1. Custom Sorting with sorted(..., key=lambda)
products = [
    {"id": 101, "name": "Laptop", "price": 1200.0},
    {"id": 102, "name": "Mouse", "price": 25.0},
    {"id": 103, "name": "Monitor", "price": 350.0}
]

# Sort products by price ascending using inline lambda key
by_price = sorted(products, key=lambda p: p["price"])


# 2. Filtering items with filter(lambda, iterable)
numbers = [12, 45, 68, 23, 90, 15]
high_numbers = list(filter(lambda x: x > 40, numbers))


# 3. Transforming items with map(lambda, iterable)
raw_prices = [100.0, 200.0, 500.0]
discounted_prices = list(map(lambda p: p * 0.85, raw_prices))


# 4. PEP 8 Clarity Check: def vs lambda
# Preferred Pythonic comprehension over map/filter + lambda for clarity
clear_high_numbers = [x for x in numbers if x > 40]


if __name__ == "__main__":
    print("Sorted by price:", [p["name"] for p in by_price])
    print("Filtered > 40:", high_numbers)
    print("Discounted prices:", discounted_prices)
🌱 Junior Track 21 Master Reference

21. When to Use Lambda vs Standard `def` Functions

📊 Decision Matrix: `def` vs `lambda` vs Comprehensions

Use Case Recommended Tool Example / Syntax Why?
Custom Sort Key Inline `lambda` sorted(items, key=lambda x: x[1]) Concise throwaway callback.
Filtering/Mapping Lists List Comprehension [x for x in data if x > 0] More readable & faster than `filter(lambda...)`.
Reusable / Multi-line Logic Standard `def` Function def process(item): ... Clean tracebacks, docstrings & testability.

⭐ Rate Track 21: Lambda Functions (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 20. Context Managers 🌱 Junior Hub ⭐ Practice 100+ Python Questions →