From: Stephen Hansen on
On 6/28/10 5:47 AM, Li Hui wrote:
> When write
> >>>i for i in range(16)
> I get "SyntaxError: invalid syntax"
>
> but When I use it like this:
> >>>def f(x):\
> ... pass
> >>>f(i for i in range(16))
>
> all is right
> I think it maybe f((i for i in range(16)))


The "<expression> for <name> in <iterator>" syntax is actually two very
different things.

One is a list comprehension, one is a generator comprehension. (Then
there's dictionary stuff later, but I shant complicate matters!)

One creates a list, the other creates a "generator" which is a kind of
iterator, which (eventually) something else can scan over to get and
operate on a sequence.

A list comprehension must be within brackets, as so:

>>> [i for i in range(4)]
[0, 1, 2, 3]

If you want to enter a generator expression on its own, you must
surround it in parens, as:

>>> (i for i in range(4))
<generator object at 0x6a2d8>

Note though, that you get a generator object and not a list or anything.
You can see what that generator would do by:

>>> gen = (i for i in range(4))
>>> for x in gen:
.... print x
....
0
1
2
3

Now, if you are entering a generator where its not 'on its own' and its
not ambiguous-- such as inside a function call-- you don't have to
surround it by its own parens. So you don't have to do f((i for i in
range(4)). You only have to group it when its own its own. I mean you
*can* wrap parens around it all the time: but just as parens don't
create tuples, the parens don't -create- the generator so much as set it
apart from possibly confusing surrounding elements when needed.

--

... Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/

From: Terry Reedy on
On 6/28/2010 10:49 AM, Stephen Hansen wrote:

> Now, if you are entering a generator where its not 'on its own' and its
> not ambiguous-- such as inside a function call-- you don't have to
> surround it by its own parens. So you don't have to do f((i for i in
> range(4)).

You need another ) on the end. That illustrates why the devs allowed one
() to be omitted ;-)
--
Terry Jan Reedy