CodeNebula
Python🔧Core Languagebeginner

Lambda Functions

Python · Core Language · Run with python3

Explanation

`lambda` creates an anonymous single-expression function. It's syntactically limited — no statements, no docstrings, no multiple expressions — by design. Lambdas are most useful as short callbacks to `sorted()`, `map()`, `filter()`, or `functools.reduce()`. For anything more complex, a named `def` is clearer.

Real-World Scenario

Sorting a list of employee dicts by department then salary requires a compound key. `sorted(employees, key=lambda e: (e["dept"], -e["salary"]))` expresses the sort criterion inline without defining a named comparator. ```python # Sort by multiple keys inline employees = [ {"name": "Alice", "dept": "eng", "salary": 120000}, {"name": "Bob", "dept": "eng", "salary": 95000}, {"name": "Carol", "dept": "hr", "salary": 80000}, ] ranked = sorted(employees, key=lambda e: (e["dept"], -e["salary"])) for e in ranked: print(f"{e['dept']:5} {e['salary']:>7,} {e['name']}") # Lambda with map and filter nums = range(1, 11) evens_sq = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums))) print(evens_sq) # [4, 16, 36, 64, 100] ```

Quick Snippet

snippet.py
# Sort by multiple keys inline
employees = [
    {"name": "Alice", "dept": "eng", "salary": 120000},
    {"name": "Bob",   "dept": "eng", "salary": 95000},
    {"name": "Carol", "dept": "hr",  "salary": 80000},
]
ranked = sorted(employees, key=lambda e: (e["dept"], -e["salary"]))
for e in ranked:
    print(f"{e['dept']:5} {e['salary']:>7,}  {e['name']}")

# Lambda with map and filter
nums = range(1, 11)
evens_sq = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))
print(evens_sq)  # [4, 16, 36, 64, 100]

Full Example

lambda_functions.py
# Compile: python3 lambda_functions.py
# Output:
# eng    95,000  Bob
# eng   120,000  Alice
# hr     80,000  Carol
# [4, 16, 36, 64, 100]

employees = [
    {"name": "Alice", "dept": "eng", "salary": 120000},
    {"name": "Bob",   "dept": "eng", "salary": 95000},
    {"name": "Carol", "dept": "hr",  "salary": 80000},
]
ranked = sorted(employees, key=lambda e: (e["dept"], e["salary"]))
for e in ranked:
    print(f"{e['dept']:5} {e['salary']:>7,}  {e['name']}")

nums = range(1, 11)
evens_sq = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))
print(evens_sq)

# Lambda in sorted key
words = ["banana", "apple", "cherry", "date"]
print(sorted(words, key=lambda w: len(w)))
Run command
python3 lambda_functions.py