12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

If you want to see what is going on inside the for, call the generator functiondirectly:>>> x = gensquares(4)>>> xYou get back a generator object that supports the iterator protocol (i.e., has a nextmethod that starts the function, or resumes it from where it last yielded a value, andraises a StopIteration exception when the end of the series of values is reached):>>> x.next( )0>>> x.next( )1>>> x.next( )4>>> x.next( )9>>> x.next( )Traceback (most recent call last):File "", line 1, in x.next( )StopIterationfor loops work with generators in the same way—by calling the next method repeatedly,until an exception is caught. If the object to be iterated over does not supportthis protocol, for loops instead use the indexing protocol to iterate.Note that in this example, we could also simply build the list of yielded values all atonce:>>> def buildsquares(n):... res = []... for i in range(n): res.append(i**2)... return res...>>> for x in buildsquares(5): print x, ':',...0 : 1 : 4 : 9 : 16 :For that matter, we could use any of the for loop, map, or list comprehensiontechniques:>>> for x in [n**2 for n in range(5)]:... print x, ':',...0 : 1 : 4 : 9 : 16 :>>> for x in map((lambda x:x**2), range(5)):... print x, ':',...0 : 1 : 4 : 9 : 16 :Iterators Revisited: Generators | 363

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!