"number-in-base" ``oneliner''

Bengt Richter bokr at oz.net
Mon Nov 1 08:20:51 CET 2004


On Mon, 01 Nov 2004 03:11:42 GMT, exarkun at divmod.com wrote:

>On Sun, 31 Oct 2004 19:00:07 GMT, bokr at oz.net (Bengt Richter) wrote:
>> [snip]
>> 
>> BTW, will anything that works in a list comprehension work in a generator expression
>> (assuming one does not depend on the generator expression having leftover outside
>> side effect bindings like the LC version)?
>> 
>
>  Nope.  For example, I don't think the code in this thread will work if converted to a generator expression.  A simplified example:
>
>    >>> x = 0 
>    >>> list(x for x in iter(lambda: x + 1, 4))
>    ( runs forever, so C-c )
>    Traceback (most recent call last):
>      File "<stdin>", line 1, in ?
>      File "<stdin>", line 1, in <generator expression>
>    KeyboardInterrupt
>    >>> [x for x in iter(lambda: x + 1, 4)]
>    [1, 2, 3]
>    >>> 
>
>  `x' in the lambda in the list comprehension resolves to a different name than `x' in the generator comprehension.
>
I had a sneaky suspicion that it _could_ be so, hoping not. But your example doesn't play fair
because you don't give x an initial condition inside the scope of the expression. E.g.,

 >>> [x for x in [0] for x in iter(lambda:x+1, 4)]
 [1, 2, 3]
 >>> list(x for x in [0] for x in iter(lambda:x+1, 4))
   File "<stdin>", line 1
     list(x for x in [0] for x in iter(lambda:x+1, 4))
              ^
 SyntaxError: invalid syntax

Well, I don't have 2.4 yet, but what does it do?
If the generator expression scope causes a closure access from lambda it should be ok, IWT.

Regards,
Bengt Richter



More information about the Python-list mailing list