map - lambda - problem
Alex Martelli
aleaxit at yahoo.com
Sun Mar 11 08:44:48 EST 2001
"Gregor Lingl" <aon.912502367 at aon.at> wrote in message
news:3AAB6078.EE50AE8D at aon.at...
[snip]
> In direct mode I got:
>
> >>> r = []
> >>> for i in range(len(n[0])-1,-1,-1):
> r.append(map(lambda x: x[i],n))
Here, i is in the global namespace, and therefore available to
functions (including lambdas).
> If i put this into a function:
>
> def rotate(piece):
> r = []
> for i in range(len(piece[0])-1,-1,-1):
> r.append(map(lambda x: x[i], piece))
Here, i is a local variable and thus (in Python 2.0) not visible
in nested scopes (including lambdas).
> Why, exactly, this behaviour. Is i now taken from some other namespace?
Local scopes don't nest (in Python 2.0). i must come from the
global namespace.
> If so, which one and why is it initialized with 0?
> How can I work around this?
Use lambda x, i=i: x[i] to inject i into the lambda's local namespace
(or, switch to Python 2.1, which does let local scopes nest).
Alex
More information about the Python-list
mailing list