[Tutor] generators

bob gailer bgailer at gmail.com
Wed Apr 4 14:39:21 CEST 2012


To Joel's and Wesley's valuable comments I add:

Calling a generator function returns a /generator object/.

 >>> def x(n):
...  for i in range(n): yield i
...
 >>> y = x(3)
 >>> print y
<generator object x at 0x01333BE8>

A generator object can be used instead of some other "iterable" (e.g.) 
in for statements.
 >>> for i in y:print i
0
1
2

x in this case is equivalent to xrange() with exactly 1 argument.

There is more that can be said regarding x.next(). x.send(), raise 
StopIteration but I've said enough for now.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120404/c60fdd2c/attachment.html>


More information about the Tutor mailing list