What exactly is “lambda” in Python? [duplicate]

Lambda is more of a concept or programming technique then anything else.

Basically it’s the idea that you get a function (a first-class object in python) returned as a result of another function instead of an object or primitive type. I know, it’s confusing.

See this example from the python documentation:

def make_incrementor(n):
  return lambda x: x + n
f = make_incrementor(42)
f(0)
>>> 42
f(1)
>>> 43

So make_incrementor creates a function that uses n in it’s results. You could have a function that would increment a parameter by 2 like so:

f2 = make_incrementor(2)
f2(3)
>>> 5

This is a very powerful idea in functional programming and functional programming languages like lisp & scheme.

Hope this helps.

Leave a Comment