Is this a bug of the lambda function

Zhu Wayne zz.wayne at gmail.com
Fri Oct 12 01:00:47 EDT 2007


Hi,
I have a short code which gives me strange results, the code is as follows:

f = [lambda x: None]*5
for j in range(0, 5):
     f[j] = lambda x: float(j)*x
print "print f[k](1.),"
for k in range(5):
     print f[k](1.),
print "expect 0. 1. 2. 3. 4."
print
print "print f[j](1.),"
for j in range(5):
     print f[j](1.),
print "expect 0. 1. 2. 3. 4."
print
print "print f[0](1.), f[1](1.), ..."
print f[0](1.), f[1](1.), f[2](1.), f[3](1.), f[4](1.)
print "expect 0. 1. 2. 3. 4."

*************************************************
The result is very strange:

print f[k](1.),
4.0 4.0 4.0 4.0 4.0 expect 0. 1. 2. 3. 4.

print f[j](1.),
0.0 1.0 2.0 3.0 4.0 expect 0. 1. 2. 3. 4.

print f[0](1.), f[1](1.), ...
4.0 4.0 4.0 4.0 4.0
expect 0. 1. 2. 3. 4.


It seems only when I use the index j (which is declear with the lambda
function), I can get expected answer, otherwise the result is not
unexpected.

Could anybody give me a possible explanation to this? Does python use kind
of pre-complie techinque to treat the lambda function? (like the macro in C
or inline function in C++)

Thanks in advance

Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071012/70d02026/attachment.html>


More information about the Python-list mailing list