generator construction

Duncan Booth duncan at rcp.co.uk
Wed Dec 4 11:26:51 EST 2002


"Eric van Riet Paap" <eric2 at vanrietpaap.com> wrote in
news:3dee2207$0$94299$e4fe514c at dreader4.news.xs4all.nl: 

> As an experiment I tried this list comprehension version:
> [yield node for node in Nodes(child)]
> 
> I understand that the list goes nowhere, but I thought it was a valid
> construction.
You thought wrongly.

> Why do I get a "SyntaxError: invalid syntax" error?

Because there is no part of the language syntax that allows you to embed a
statement such as "yield node" or "import sys" in the middle of an
expression. 

Even if the language syntax did allow this it would seem to be self
defeating since the point of a generator is to avoid building lists. 

If you want to cut your original for loop down from two lines to one, you
can do that simply by writing it all on one line: 

    	for node in Nodes(child): yield node



More information about the Python-list mailing list