[Python-Dev] accumulator display syntax
Phillip J. Eby
pje at telecommunity.com
Fri Oct 17 15:20:31 EDT 2003
At 01:57 PM 10/17/03 -0500, Skip Montanaro wrote:
> >> But, indexing does stretch quite far in the current Python syntax and
> >> semantics (in Python's *pragmatics* you're supposed to use it far
> >> more restrainedly).
> Guido> Which is why I didn't like the 'sum[x for x in S]' notation much.
> Guido> Let's look for an in-line generator notation instead. I like
> Guido> sum((yield x for x in S))
> Guido> but perhaps we can make this work:
> Guido> sum(x for x in S)
>Forgive my extreme density on this matter, but I don't understand what
> (yield x for x in S)
>is supposed to do. Is it supposed to return a generator function which I
>can assign to a variable (or pass to the builtin function sum() as in your
>example) and call later, or is it supposed to turn the current function into
>a generator function (so that each executed yield statement returns a value
>to the caller of the current function)?
Neither. It returns an *iterator*, conceptually equivalent to:
for x in S:
temp = temp()
Except of course without creating a 'temp' name. I suppose you could also
think of it as:
(lambda: for x in S: yield x)()
except of course that you can't make a generator lambda.
If you look at it this way, then you can consider [x for x in S] to be
shorthand syntax for list(x for x in S), as they would both produce the
same result. However, IIRC, the current listcomp implementation actually
binds 'x' in the current local namespace, whereas the generator version
would not. (And the listcomp version might be faster.)
More information about the Python-Dev