A lambda function (or more accurately, a lambda expression) is simply a function you can define on-the-spot, right where you need it. For example,
f = lambda x: x * 2
is exactly the same thing as
def f(x):
return x * 2
And when I say exactly, I mean it -- they disassemble to the same bytecode. The only difference between the two is that the one defined in the second example has a name.
Lambda expressions become useful because creating one is not a statement, which means that, as others have already answered, you can do
print iterator(lambda x: x / 4 + 12, 100, 5)
to get precisely what you want.
The main difference between lambda expressions and regular functions, however, is that lambdas are more limited. Lambdas can only contain expressions, not statements. An expression is anything you can put on the right side of an =
assignment. (if you want to get more pedantic, Python defines an expression as http://docs.python.org/2/reference/expressions.html )
What this means is a lambda expression can not assign to a variable (in fact, it can't have local variables at all, other than its parameters). It can't print (unless it calls another function that does). It can't have a for loop, a while loop, an if test (other than the ternary operator x if cond else y
), or a try/except block.
If you need to do any of those, just define a regular function. In fact, any time you think you want to use a lambda, think twice. Wouldn't the code be more readable if you used a regular function? Isn't that lambda expression something you'd like to reuse somewhere else in your code?
In the end, always do what leads to the most readable and maintainable code. There is no difference between lambdas and normal functions as far as performance is concerned.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…