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 
... mroot = n ** 0.5
... while m <= mroot:
... if s[i]:
... while j<half:
... yield 2
... for x in s:
... if x: yield x
>>> x = primes(11)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
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