λ Python Lambda Functions — Small Anonymous Functions
Lambda functions are compact, one-line anonymous functions. Perfect for short operations passed to sort(), filter(), and map().
For complex logic, use a named function instead of lambda — PEP8 says not to assign lambdas to variables (just use def).
💻 Code Example:
# Basic lambda square = lambda x: x**2 print(square(7)) # 49 # Lambda with multiple arguments add = lambda a, b: a + b print(add(10, 20)) # 30 # Lambda with sorted() — real use case pynfinity_scores = [ {'user': 'santoshtvk', 'score': 95}, {'user': 'dhruv', 'score': 88}, {'user': 'tvk', 'score': 99}, ] # Sort by score descending ranked = sorted(pynfinity_scores, key=lambda x: x['score'], reverse=True) for r in ranked: print(r['user'], r['score']) # Lambda with filter() numbers = [5, 12, 3, 21, 8, 14, 2] above_10 = list(filter(lambda x: x > 10, numbers)) print(above_10) # [12, 21, 14] # Lambda with map() prices_usd = [10, 25, 50] prices_inr = list(map(lambda usd: usd * 83, prices_usd)) print(prices_inr) # [830, 2075, 4150]
| Concept | Key Takeaway |
|---|---|
| sorted(list, key=lambda) | Sort by a custom criteria |
| filter(lambda, list) | Keep only elements matching condition |
| map(lambda, list) | Transform every element |
| max/min(list, key=lambda) | Find max/min by custom criteria |
Keep exploring and happy coding! 🚀