[Pythonmac-SIG] Nested lists

Jack Jansen jack@oratrix.nl
Tue, 29 Feb 2000 10:50:07 +0100


> When I try to implement this in a function I get something like:
> 
> def mklist(num):
>     return map(lambda x:[] * num, range(num))
>     
> and mklist(4) yields [[], [], [], [], [], []]
> 
> This works in 'Python interactive'. In a normal Python window I get a NameError.

This is bound to be in an FAQ somewhere: the lambda has its own namespace, 
i.e. within the lambda body you can see (1) names within that body and (2) 
global names. So, you can't see the names in the intermedeate function.

The workaround is to abuse the parameter mechanism:
def mklist(num):
	return map(lambda x, num=num: []*num, range(num))

--
Jack Jansen             | ++++ stop the execution of Mumia Abu-Jamal ++++
Jack.Jansen@oratrix.com | ++++ if you agree copy these lines to your sig ++++
www.oratrix.nl/~jack    | see http://www.xs4all.nl/~tank/spg-l/sigaction.htm