Skip to content

Lambda Functions#

Lambda expressions create small anonymous functions: lambda args: expression. They are expressions (not statements) — useful for short callbacks and key= functions.

How to use this page

Use lambdas for one-liners; use def when logic grows. See Higher Order Functions.

At a glance
Track Python Advanced → Advanced Functions
Sections 5 major topics
Outline Use the right-hand TOC to jump

Topics: Syntax · Common uses · Lambda vs def · Closures with lambda · Alternatives

  1. Syntax
  2. Common uses
  3. Lambda vs def
  4. Closures with lambda
  5. Alternatives

Syntax#

lambda x: x * 2
lambda x, y: x + y
lambda: 42
lambda *args: sum(args)
lambda x, y=10: x + y   # default allowed

Restrictions:

  • Body is one expression — no statements, no assignments (until walrus in expression context)
  • No annotations on parameters (use def for typed APIs)
  • No docstring

Common uses#

Sorting keys#

sorted(students, key=lambda s: s.score)
sorted(points, key=lambda p: (p[0], p[1]))

map / filter#

list(map(lambda x: x.strip(), lines))
list(filter(lambda x: x > 0, nums))

Prefer comprehensions when readable:

[x.strip() for x in lines]
[x for x in nums if x > 0]

Delayed callbacks#

buttons = []
for i in range(3):
    buttons.append(lambda i=i: print(i))   # bind i!

Lambda vs def#

lambda def
Name Anonymous Named
Body Single expression Statements
Tracebacks Shows <lambda> Shows function name
Debugging Harder Easier
Best for key=, short callbacks Everything non-trivial

Rule: if it doesn't fit on one line comfortably, use def.


Closures with lambda#

def power(n):
    return lambda x: x ** n

square = power(2)
square(4)   # 16

Same late-binding rules as nested def — see Closures.


Alternatives#

# operator module — no lambda needed
from operator import itemgetter, attrgetter
sorted(rows, key=itemgetter(1))
sorted(users, key=attrgetter("name"))

# partial
from functools import partial
double = partial(pow, 2)   # careful: pow(2, x) vs pow(x, 2)

Interview traps (quick reference)#

Trap What goes wrong Safe approach
Lambda in loop without bind All use final loop var lambda i=i: or factory
Complex lambda Unreadable def helper
Statement in lambda SyntaxError Use def
Side effects in lambda Hard to test Named function

Mental model checklist#

  1. What can a lambda body contain?
  2. When is operator.itemgetter better than lambda?
  3. Why name lambdas in loop callbacks carefully?

What's next#

Topic Page
Higher-order functions Higher Order Functions
Partial Partial Functions
Closures Closures