Yield

Danny Colligan dannycolligan at gmail.com
Thu Nov 16 10:32:53 EST 2006


Now that we're on the subject, what are the advantages of using
generators over, say, list comprehensions or for loops?  It seems to me
that virtually all (I won't say everything) the examples I've seen can
be done just as easily without using generators.  For example,
Fredrik's initial example in the post:

>>> a = [1,2,3]
>>> for i in a: print i
...
1
2
3
>>> sum(a)
6
>>> [str(i) for i in a]
['1', '2', '3']
>>>

Carsten mentioned that generators are more memory-efficient to use when
dealing with large numbers of objects.  Is this the main advantage of
using generators?  Also, in what other novel ways are generators used
that are clearly superior to alternatives?

Thanks in advance,

Danny

On Nov 16, 3:14 am, John Machin <sjmac... at lexicon.net> wrote:
> On 16/11/2006 7:00 PM, Fredrik Lundh wrote:
>
> > John Machin wrote:
>
> >>> I would like to thanks Fredrik for his contribution to improve that.
>
> >> Call me crazy, but after an admittedly quick read, the version on the
> >> wiki seems to be about word for word with on the docs.python.org version.
>
> > maybe he was thinking about the article I posted, or the FAQ link I
> > posted in a followup:
>
> >    http://effbot.org/pyfaq/what-is-a-generator.htm
>
> > which was based on my article and the glossary entry from the tutorial:
>
> >    http://effbot.org/pytut/glossary.htm#generatorQuite possibly.
>
>
>
> >> Could you please tell us how you think the wiki version is an
> >> improvement?
>
> > an "add comment" link?  direct URL:s for all concepts in the language?
> > extensive hyperlinking?  semantic retargetable markup?Yes, they're great. Maybe I was thinking about the text contents only :-)
> 
> Cheers,
> John




More information about the Python-list mailing list