thanks, perhaps you'll rind this which I used to show how generators are like iterators:
>>> # Generators are iterators on steroids ... >>> # review: ... l = [1,2,3] >>> for n in l: ... print n ... 1 2 3 >>> >>> >>> l_iter = iter(l) >>> for n in l_iter: ... print n ... 1 2 3 >>> >>> >>> l_iter = iter(l) >>> l_iter.next() 1 >>> l_iter.next() 2 >>> l_iter.next() 3 >>> l_iter.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> # Note the "StopIteration" -- this happens behind the scenes ... >>> >>> >>> # enough review lets write a generator ... >>> def gen123(): ... l = [1,2,3] ... for n in l: ... yield n ... >>> # What is "yield"? It returns a value like return but leaves the function to resume excution after the yield. ... >>> # As with the above iterator: ... >>> g = gen123() >>> for n in g: ... print n ... 1 2 3 >>> >>> >>> #or ... g = gen123() >>> g.next() 1 >>> g.next() 2 >>> g.next() 3 >>> g.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> >>> >>> # OK, so it does the same thing as an iterator? Not really. ... # Remember I said it leaves the function to resume execution after the yield? ... # well all of the function's internal state is maintained. ... # an example fron PEP 255 which introduced generators: ... >>> def fib(): ... a, b = 0, 1 ... while 1: ... yield b ... a, b = b, a+b ... >>> f = fib() >>> for n in range(0,6): ... print f.next() ... 1 1 2 3 5 8 >>> >>> # Note that between calls to f.next() the values of the variables a and b are retained. On Thu, Mar 11, 2010 at 11:55 PM, <[email protected]> wrote: > > Though I missed much of your talk, I benefited from the discussion that > followed, so, Thanks James. > > Jon > > > On Thu, 11 Mar 2010, James Thiele wrote: > > Yeah. I gave a poorly received talk on generators. >> > -- No electrons were harmed in the creation of this email.
