Peng Yu wrote: > http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt > > The explanation of yield is not clear to me, as I don't know what a > generator is. I see the following example using 'yield'. Could > somebody explain how 'yield' works in this example? Thank you! > > def brange(limit): > i = 0 > while i < limit: > yield i > i += 1
Let's make this as simple as possible. >>> def g(x): ... yield x ... >>> p = g(4) >>> type(p) <type 'generator'> >>> type(type(p)) <type 'type'> So there you have it. Generator is an instance of 'type', hence a new-style class, even though it is returned by a simple looking function. >>> p.next() 4 What were you expecting? >>> type(g) <type 'function'> g is a function that returns a generator. The yield statement does two things. It states what is to be returned by the generator's next() method and it also defines g as a function that returns a generator. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list