Content deleted Content added
Less silly generator example |
|||
Line 225:
Introduced in Python 2.2 as optional feature and finalized in version 2.3, [[Generator (computer science)|generators]] are Python's mechanism for [[lazy evaluation]] of a function that would otherwise return a space-prohibitive or computationally intensive list.
for i in xrange(N):▼
yield i▼
import sys
You can now use the generator generate_ints:▼
def generate_primes(max=sys.maxint):
primes = []
n = 2
while n < max:
composite = False
if not n % p:
composite = True
break
if not composite:
primes.append(n)
n += 1
To use this function simply call, e.g.:
for i in generate_primes(100):
▲ print i,You can now use the generator generate_ints:
The definition of a generator appears identical to that of a function, except the keyword <code>yield</code> is used in place of <code>return</code>. However, a generator is an object with persistent state, which can repeatedly enter and leave the same dynamic extent. A generator call can then be used in place of a list, or other structure whose elements will be iterated over. Whenever the <code>for</code>-loop in the example requires the next item, the generator is called, and yields the next item.
==== Generator Expressions ====
|