Yield

Danny Colligan dannycolligan at gmail.com
Thu Nov 16 17:09:14 CET 2006


> The more trivial the example, the harder it is to see the advantage.

I absoultely agree.  Thanks for pointing me out to some real-world
code.  However, the function you pointed me to is not a generator
(there is no yield statement... it just returns the entire list of
primes).  A generator version would be:

>>> def primes(n):
...     if n<2: yield []
...     s=range(3,n+1,2)
...     mroot = n ** 0.5
...     half=(n+1)/2-1
...     i=0
...     m=3
...     while m <= mroot:
...         if s[i]:
...             j=(m*m-3)/2
...             s[j]=0
...             while j<half:
...                 s[j]=0
...                 j+=m
...         i=i+1
...         m=2*i+3
...     yield 2
...     for x in s:
...         if x: yield x
...
>>> x = primes(11)
>>> x.next()
2
>>> x.next()
3
>>> x.next()
5
>>> x.next()
7
>>> x.next()
11
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>

Danny Colligan

On Nov 16, 10:49 am, "Richard Brodie" <R.Bro... at rl.ac.uk> wrote:
> "Danny Colligan" <dannycolli... at gmail.com> wrote in messagenews:1163691173.737911.130410 at i42g2000cwa.googlegroups.com...
>
> > 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.The more trivial the example, the harder it is to see the advantage.
> Suppose you wanted to sum the first 10000 primes. A quick Google
> fins you Wensheng Wang's recipe:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178
> Just add print sum(primes(10000)), and you're done.




More information about the Python-list mailing list