Skip to main content

Functions

Lambda Functions

Complete lesson for Lambda Functions using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Lambda Functions

Section: Functions. Python lambda functions — anonymous one-expression callables for key= and short callbacks.

What is a lambda?

  • A **lambda** creates a small anonymous function: lambda params: expression.
  • The body must be a single expression (not statements like if blocks or assignments).
  • **Real-life:** a sticky note formula instead of a full labeled recipe card (def).
FormMeaningExample
lambda x: x+1One argIncrement
lambda a, b: a*bTwo argsProduct
lambda: 42No argsConstant
lambda **kw: kwVarargs styleCollect kwargs
inc = lambda x: x + 1
mul = lambda a, b: a * b
print(inc(4), mul(3, 5))
print((lambda n: n * n)(6))

lambda vs def

  • def names a function, allows multiple statements, docstrings, and clearer stack traces.
  • lambda is for short throwaway callables passed inline.
  • If you need a name and reuse, prefer def.
def square_def(n):
    return n * n

square_lambda = lambda n: n * n
print(square_def(5), square_lambda(5))
print(square_def.__name__, square_lambda.__name__)

Using lambda with sorted

  • sorted(iterable, key=fn) uses fn(item) for comparison keys.
  • Lambdas shine for sorting by field, length, or reverse tricks.
  • Stable sort keeps original order among equal keys.
words = ["pear", "fig", "apple", "kiwi"]
print(sorted(words, key=lambda w: len(w)))
pairs = [("Ada", 90), ("Bob", 75), ("Cia", 90)]
print(sorted(pairs, key=lambda p: (-p[1], p[0])))

map and filter with lambda

  • map(fn, iterable) applies fn lazily; wrap with list to materialize.
  • filter(pred, iterable) keeps items where pred is true.
  • List comprehensions are often clearer; know both for interviews.
nums = [1, 2, 3, 4, 5]
print(list(map(lambda n: n * 2, nums)))
print(list(filter(lambda n: n % 2 == 1, nums)))

Default arguments in lambda

  • Lambdas support defaults: lambda x, y=10: x + y.
  • Same mutable-default warning applies.
  • Keyword-only patterns are possible but rarely worth the noise in a lambda.
greet = lambda name, title="Ms.": f"{title} {name}"
print(greet("Ada"))
print(greet("Ada", title="Dr."))

Lambdas in data structures

  • You can store lambdas in dicts to build simple dispatch tables.
  • Useful for tiny calculators or command maps.
  • For large dispatch, use functions or classes instead.
ops = {
    "add": lambda a, b: a + b,
    "sub": lambda a, b: a - b,
    "mul": lambda a, b: a * b,
}
print(ops["add"](10, 3))
print(ops["mul"](4, 5))

Closures: capturing variables

  • A lambda can read variables from the enclosing scope.
  • Late binding caution: in loops, lambdas capture the variable, not the value at creation — use default args to freeze.
funcs_bad = [lambda: i for i in range(3)]
print([f() for f in funcs_bad])

funcs_ok = [lambda i=i: i for i in range(3)]
print([f() for f in funcs_ok])

Immediate invocation and higher-order use

  • (lambda x: x + 1)(5) calls immediately — rarely needed.
  • Pass lambdas to APIs expecting callables: key=, callbacks, min/max.
people = [
    {"name": "Ada", "age": 36},
    {"name": "Bob", "age": 29},
    {"name": "Cia", "age": 41},
]
print(min(people, key=lambda p: p["age"]))
print(max(people, key=lambda p: p["name"]))
L2

Advanced — Lambda Functions

Limitations of lambda

  • No statements: cannot use return, assert, multi-line if, assignments (except walrus in 3.8+ carefully).
  • Harder debugging (<lambda> in tracebacks).
  • Nested ternary expressions become unreadable fast — switch to def.
abs_like = lambda n: n if n >= 0 else -n
print(abs_like(-9), abs_like(4))
# Prefer def for clarity when branching grows

functools and operator instead of lambda

  • operator.itemgetter, attrgetter, methodcaller often replace simple lambdas.
  • functools.reduce can use lambda but readability suffers; consider an explicit loop.
from operator import itemgetter
from functools import reduce

rows = [("a", 2), ("b", 1), ("c", 3)]
print(sorted(rows, key=itemgetter(1)))
print(reduce(lambda acc, n: acc + n, [1, 2, 3, 4], 0))

Sorting with complex keys

  • Return a tuple from the key function for multi-level sort.
  • Negate numbers for descending while keeping ascending tie-breakers on strings.
students = [
    {"name": "Cia", "grade": "A", "score": 88},
    {"name": "Ada", "grade": "A", "score": 92},
    {"name": "Bob", "grade": "B", "score": 95},
]
ordered = sorted(
    students,
    key=lambda s: (s["grade"], -s["score"], s["name"]),
)
print([s["name"] for s in ordered])

When to forbid lambdas in a codebase

  • Style guides often ban non-trivial lambdas for maintainability.
  • Replace with def once you need a name, docstring, type hints, or multiple uses.
  • Inline lambdas that close over changing loop vars are a frequent bug source.
def score_key(student):
    """Sort by grade asc, score desc, name asc."""
    return (student["grade"], -student["score"], student["name"])

students = [{"name": "Ada", "grade": "A", "score": 92}]
print(sorted(students, key=score_key))
L3

Tricky Interview Points

Q1) What is a lambda function in Python?

Answer An anonymous function defined with the lambda keyword whose body is a single expression that is returned automatically.

Q2) Can a lambda contain multiple statements?

Answer No. Only one expression is allowed. Use def for multi-statement logic.

Q3) Why do lambdas show __name__ as <lambda>?

Answer They are anonymous; unless assigned, they have no meaningful function name for debugging.

Q4) Common use cases for lambda?

Answer Short key functions for sorted/min/max, simple map/filter callbacks, and tiny dispatch entries.

Q5) What is the loop late-binding gotcha?

Answer Lambdas created in a loop capture variables by name; they see the final value unless you bind with default args like lambda i=i: i.

Q6) lambda vs list comprehension?

Answer They solve different jobs. Comprehensions build collections; lambdas create callables. Prefer comprehensions over map(lambda ...) for clarity.

Q7) Are lambdas faster than def?

Answer Not meaningfully. Choose based on readability, not micro-performance myths.

Q8) Can lambdas take *args and **kwargs?

Answer Yes. Example: lambda *a, **k: (a, k).

Q9) How do you sort a list of dicts by a field?

Answer sorted(rows, key=lambda r: r["field"]) or itemgetter("field").

Q10) When should you avoid lambda?

Answer When logic is complex, reused, needs docs/type hints, or hurts stack traces — use def instead.

Q11) Does lambda create a closure?

Answer Yes, it can close over enclosing-scope variables like a nested def.

L4

Simple Programs

Sort words by last character

words = ["banana", "pear", "apple", "fig"]
print(sorted(words, key=lambda w: w[-1]))

Dispatch calculator

calc = {
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "*": lambda a, b: a * b,
    "/": lambda a, b: a / b,
}
for op in ["+", "*", "-"]:
    print(op, calc[op](12, 3))

Freeze loop variables

makers = [lambda n=n: n * n for n in range(1, 5)]
print([m() for m in makers])

Highest scoring student

class_list = [
    {"name": "Ada", "score": 91},
    {"name": "Bob", "score": 87},
    {"name": "Cia", "score": 95},
]
best = max(class_list, key=lambda s: s["score"])
print(best["name"], best["score"])

map + filter pipeline

nums = range(1, 11)
result = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))
print(result)
L5

Problem Solving Tricks

  • Prefer operator.itemgetter(i) over lambda x: x[i] for simple indexing.
  • Freeze loop vars with defaults: lambda x=x: ....
  • For descending numeric sort: key=lambda x: -x (or reverse=True).
  • Multi-key sort: return a tuple from the lambda.
  • Do not nest ternary soups inside lambdas — switch to def.
  • Assigning a lambda to a name is a style smell if a def would be clearer.
  • min(seq, key=lambda ...) finds objects by computed criterion.
  • Use comprehensions instead of list(map(lambda ...)) when transforming sequences.
  • Remember lambdas still obey LEGB / closure rules.
L6

Practice Programs List

  1. Sort a list of emails by the domain part after @ using a lambda.
  2. Rewrite list(map(lambda x: x+1, nums)) as a list comprehension.
  3. Build a dict of operation lambdas for +, -, *, // and demo each.
  4. Show the late-binding bug with a loop, then fix it.
  5. Use max with a lambda to pick the longest string in a list.
  6. Sort student records by GPA desc then name asc.
  7. Replace a sorting lambda with itemgetter and compare readability.
  8. Write a lambda with a default argument and call it both ways.
  9. Create a list of closures that multiply by 2, 3, 4 respectively.
  10. Decide for three examples whether lambda or def is more appropriate.
  11. Use filter+lambda to keep only palindromic words from a list.