Help with lambda

Jonathan Gardner jgardner at
Thu Feb 18 23:26:33 CET 2010

On Feb 18, 4:28 am, lallous <elias.bachaal... at> 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

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).

More information about the Python-list mailing list