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

exarkun at divmod.com exarkun at divmod.com
Mon Nov 1 07:59:01 EST 2004


On Mon, 01 Nov 2004 07:20:51 GMT, bokr at oz.net (Bengt Richter) wrote:
>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
> 

  I'm not sure what "playing fair" means here :)  I gave an example of a list comprehension that behaves differently when trivially rewritten as a generator comprehension, without relying on the one behavioral difference you explicitly omitted.  I do appear to have been wrong about this change applying to the number_in_base function, though.

  Jp



More information about the Python-list mailing list