Lesson 64 +10 XP

Lambda

Lambda

A lambda is a tiny, anonymous function you write on one line.

The syntax

lambda arguments : expression

A simple lambda

x = lambda a : a + 10
print(x(5))  # 15

More arguments

x = lambda a, b : a * b
print(x(5, 6))  # 30

Why lambdas?

They're handy for short functions you use once, especially with built-ins like map() and filter():

nums = [1, 2, 3, 4]
doubled = list(map(lambda n: n * 2, nums))
print(doubled)  # [2, 4, 6, 8]

Lambda in a function

A common trick: return a lambda from a function.

def make_multiplier(n):
    return lambda a : a * n

doubler = make_multiplier(2)
print(doubler(11))  # 22

When NOT to use a lambda

If the logic is more than one simple expression, use a normal def. Lambdas can't contain statements.

TL;DR

  • lambda args: expression makes a one-line function.
  • It has no name and no statements.
  • Great with map(), filter(), and short callbacks.
  • For anything complex, use def.