λ Lambda Functions
A lambda function is a small anonymous function. It can take any number of arguments, but can only have one expression.
Mastering this concept will significantly boost your Python data science skills!
💻 Code Example:
# 1. Basic lambda — contrast with def double_def = lambda x: x * 2 # PEP8 recommends def for reuse add = lambda a, b: a + b clamp = lambda x, lo, hi: max(lo, min(x, hi)) print(double_def(7)) # 14 print(add(10, 25)) # 35 print(clamp(150, 0, 100)) # 100 # 2. sorted() with key=lambda pynfinity_users = [ {"name": "santoshtvk", "score": 95, "courses": 3}, {"name": "dhruv", "score": 88, "courses": 2}, {"name": "tvk", "score": 72, "courses": 4}, {"name": "alice", "score": 60, "courses": 1}, ] # Sort by score descending by_score = sorted(pynfinity_users, key=lambda u: u["score"], reverse=True) # Sort by multiple keys — courses desc, then score desc by_multi = sorted(pynfinity_users, key=lambda u: (-u["courses"], -u["score"])) print("\nTop user:", by_score[0]["name"]) # santoshtvk print("Multi-sort:", [u["name"] for u in by_multi]) # 3. filter() — only users with score >= 80 high_scorers = list(filter(lambda u: u["score"] >= 80, pynfinity_users)) print("High scorers:", [u["name"] for u in high_scorers]) # 4. map() — transform all users with_grade = list(map( lambda u: {**u, "grade": "A" if u["score"] >= 90 else "B" if u["score"] >= 75 else "C"}, pynfinity_users )) for u in with_grade: print(f" {u['name']:<15} {u['score']} → {u['grade']}") # 5. max() and min() with lambda top_user = max(pynfinity_users, key=lambda u: u["score"]) print("\nTop user:", top_user["name"]) most_active = max(pynfinity_users, key=lambda u: u["courses"]) print("Most active:", most_active["name"]) # 6. functools.reduce with lambda from functools import reduce total_score = reduce(lambda acc, u: acc + u["score"], pynfinity_users, 0) print(f"\nCombined score: {total_score} | Avg: {total_score/len(pynfinity_users):.1f}")
Keep exploring and happy coding! 💻