explain this function to me, lambda confusion

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Wed May 7 18:44:10 EDT 2008


On 7 mai, 23:38, globalrev <skanem... at yahoo.se> wrote:
> i have a rough understanding of lambda but so far only have found use
> for it once(in tkinter when passing lambda as an argument i could
> circumvent some tricky stuff).
> what is the point of the following function?
>
> def addn(n):
>                 return lambda x,inc=n: x+inc

It returns a function that accept one argument and return the result
of the addition of this argument with the argument passed to addn.

FWIW, Python's lambda is just a shortcut to create a very simple
function, and the above code is canonically written as:

def makeadder(n):
  def adder(x):
    return n + x
  return adder

> if i do addn(5) it returns
>
(snip)

> <function <lambda> at 0x01D81830>
>
> ok? so what do i write to make it actually do something.

add5 = addn(5)
add5(1)
=> 6
add5(2)
=> 7

add42 = addn(42)
add42(1)
=> 43

> and is the
> inc=n necessary i cant do x+n?

In this case, it's not. This version does exactly the same thing
AFAICT:

def addn(n):
    return lambda x: x+n




More information about the Python-list mailing list