[Tutor] Cannot Understand

Bob Gailer bgailer at alum.rpi.edu
Fri Mar 10 23:58:07 CET 2006


Edgar Antonio Rodriguez Velazco wrote:
> Hi,
> Could you please explain this code?.
>
> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1
You've had 2 replies that dissect the "expression". I fear they might 
not make lambda itself clear, so I will add my explanation.

lambda is a Python operator that creates a function. It's syntax is 
quite different from other operators:

    lambda optional-list-of-arguments : expression to be evaluated and 
returned by the function

The statement you posted is equivalent to:

    def f(n):
        return n-1 + abs(n-1) and f(n-1)*n or 1

The other replies do a good job of dissecting the expression part, which 
recursively calculates the (did you know what?) factorial of n.

Despite other claims of ugliness lambda has its use, especially in 
places where you don't need the function bound to a variable. Example 
would be a dictionary of functions to do arithmetic where the operator 
is specified by a user.
    calculator = {'+' : lambda a,b: a+b, '*' : lambda a,b: a*b, etc.} #

The user, via some input mechanism provides numbers for n1 and n2, and a 
symbol for operation. Then
    result = calculator[operation](n1, n2)


More information about the Tutor mailing list