This is an old copy of the Python FAQ. The information here may be outdated.

Why can't lambda forms contain statements?

Python’s lambda forms cannot contain statements because Python’s syntactic framework can’t handle statements nested inside expressions. However, in Python, this is not a serious problem. Unlike lambda forms in other languages, where they add new functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.

Functions are already first class objects in Python, and can be declared in a local scope. Therefore the only advantage of using a lambda form instead of a locally-defined function is that you don’t need to invent a name for the function — but that’s just a local variable to which the function object (which is exactly the same type of object that a lambda form yields) is assigned!

In other words,

def func():
    v = map(lambda x: x+3, range(10))

and

def func():
    def adder(x):
        return x+3
    v = map(adder, range(10))

are equivalent. While the first form is shorter, the second form makes it easier to add more code (including debugging statements) to the function.

CATEGORY: general design

 

A Django site. rendered by a django application. hosted by webfaction.