[Tutor] Is generator function reusable?

Kent Johnson kent37 at tds.net
Sat Mar 17 15:28:33 CET 2007

ammar azif wrote:
> Lets say a generator function instance is created and has finished its 
> iteration.
> Can that instance be reused again? can it accept anymore values? or we 
> should discard it and create a new generator instance.

In general, no, you can't reuse any iterator, including the generator 
created by calling a generator function. Iterators go through their 
values once, then raise StopIteration on any further accesses.

In Python 2.5 you can pass values into a generator by calling next() 
with a value. You could use this to create a generator that can be 
reset. But more commonly you would just call the generator function 
again and create a new generator instance.


More information about the Tutor mailing list