Lambda functions that return a list built through a list comprehension
used in a list comprehension cause Python to die.
Example:
[ (lambda a:[a**i for i in range(a+1)])(j) for j in range(5) ]
You can use "map" instead of list comprehension of course (as I
illustrate in my example output), so this isn't a big deal, but I think it
ought to work.
What follows this paragraph is an interactive session in Python, where
I illustrate the workings of my lambda function to illustrate that it
does work correctly in several circumstances, but not in a list
comprehension. I've done this with OS X Python 2.3b1, 2.2.2, 2.2,
and Solaris Python 2.2a2 with the same results.
=========
Python 2.3b1 (#1, May 6 2003, 01:40:43)
[GCC 3.1 20020420 (prerelease)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> (lambda a:[a**i for i in range(a+1)])(5)
[1, 5, 25, 125, 625, 3125]
>>> f = lambda a:[a**i for i in range(a+1)]
>>> [ f(i) for i in range(5) ]
[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]
>>> map(lambda a:[a**i for i in range(a+1)], range(5))
[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]
>>> [ (lambda a:[a**i for i in range(a+1)])(j) for j in range(5) ]
Fatal Python error: unknown scope for _[1] in <lambda>(1) in <stdin>
symbols: {'a': 12, '_[2]': 2, 'range': 8, 'i': 10}
locals: {'a': 0, '_[2]': 1, 'i': 2}
globals: {'range': True}
Abort
|