Help with lambda

Xavier Ho contact at xavierho.com
Thu Feb 18 13:45:58 CET 2010


I'm looking at your code and was thinking ... why writing code that is
difficult to understand?

To answer your question though, they're different because in case "f", your
lambda experssion is only evaluated once. That means the variable 'n' is
ever only created once, and replaced repeatedly. In the second case "g", the
function is only ever created once, and in effect, the lambda expression is
evaluated as a new expression every time the function is called. That's why
it may have been what you wanted.

Seriously though, you should use a generater instead. And if that doesn't
work for you, just make a function mate. Way easier to read, and you don't
have to have ugly calls like f[0](3).

>>> def powers(n):
...     for x in xrange(2,5):
...         yield x ** n
...
>>> for result in powers(3):
...     print result
...
8
27
64

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100218/007e9150/attachment.html>


More information about the Python-list mailing list