Python (programming language): Difference between revisions

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.
 
OneThis is an example fromto lazily generate the python.orgprime websitenumbers:
<!-- this example sucks, since no need for the generate_ints generator, with xrange being an iterable. -->
def generate_ints(N):
for i in xrange(N):
yield i
<!--the above is not incorrect. xrange is the proper way to generate a range in Python, providing you don't need a list. xrange returns an iterator; range returns a list. thus, xrange consumes less memory.-->
 
import sys
You can now use the generator generate_ints:
def generate_primes(max=sys.maxint):
primes = []
n = 2
while n < max:
composite = False
for ip in xrange(N)primes:
if not n % p:
composite = True
break
if not composite:
primes.append(n)
yield in
n += 1
 
To use this function simply call, e.g.:
for i in generate_ints(N):
for i in generate_primes(100):
print i
print i,You can now use the generator generate_ints:
 
Note that the variable ''N'' should be defined before executing the second piece of code.
 
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 ====