On Feb 18, 4:28 am, lallous <elias.bachaal...@gmail.com> wrote:
>
> f = [lambda x: x ** n for n in xrange(2, 5)]

This is (pretty much) what the above code does.

>>> f = []
>>> n = 2
>>> f.append(lambda x: x**n)
>>> n = 3
>>> f.append(lambda x: x**n)
>>> n = 4
>>> f.append(lambda x: x**n)
>>> n = 5
>>> f.append(lambda x: x**n)

Now, when you call f[0], you are calling "lambda x: x**n". What is
"n"?

You need some way of creating a new namespace and a new variable
pointing to what "n" was for that iteration. Python doesn't create a
namespace for every iteration like some languages may. You have to be
more explicit about that. After all, what would you expect the
following code to do?

>>> n = 5
>>> f = [lambda x: x**n for i in range(2,5)]
>>> n = 2
>>> f[0][5]

Or, just call a function that will have a new namespace *for every
call* and generate a function within each execution of that function
(like make_power does).
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to