map - lambda - problem

Carel Fellinger cfelling at iae.nl
Sun Mar 11 10:37:13 EST 2001


Gregor Lingl <aon.912502367 at aon.at> wrote:
...
> In direct mode I got:

>>>> r = []
>>>> for i in range(len(n[0])-1,-1,-1):
>         r.append(map(lambda x: x[i],n))
...
> 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))
>     return r
...
> Why, exactly, this behaviour. Is i now taken from some other namespace?

Bingo, you got it!

Python used to know only three scopes: local, global and builtin.
And lambda starts a new local scope, hiding rotate's local scope.
Newer versions of Python have nested function-scope, that is within
functions/lambdas scopes nest.

The work around used to be to pass the needed local vars explicitly to
the function/lambda like:

    def rotate(piece):
    	r = []
    	for i in range(len(piece[0])-1,-1,-1):
    	    r.append(map(lambda x, i=i: x[i], piece))
    	return r

You can do the same with named functions, like:

    def rotate(piece):
    	r = []
    	for i in range(len(piece[0])-1,-1,-1):
            def sub(x, i=i):
                return x[i]
    	    r.append(map(sub, piece))
    	return r

Or you could forgo that local i alltogether, like:

    def rotate(piece):
        r = apply(map, (None,) + list(piece))
        r.reverse()
        return r
-- 
groetjes, carel



More information about the Python-list mailing list