[Tutor] I am terribly confused about "generators" and "iterators".. Help me

Kent Johnson kent37 at tds.net
Wed Nov 1 17:18:27 CET 2006


Kent Johnson wrote:
> Bob Gailer wrote:
>> Asrarahmed Kadri wrote:
>>>  
>>> What are generators and iterators...??And why are they are needed..??
>>>  
>>> I can do my stuff with a 'for' or a 'while' loop.. so why do I need an 
>>> ITERATOR..?
>> iterators & generators do not replace while or for loops! 
> 
> No, actually iterators and generators are the foundation of for loops. 
> Whenever you write a for loop, Python creates an iterator to return the 
> values that are assigned to the loop variables.
> 
> Writing your own iterator is a way to make a new kind of thing that can 
> be iterated in a for loop. Generators are a convenient way to make 
> iterators. They can be used to encapsulate loop logic. For some examples 
> see these recent threads:
> http://thread.gmane.org/gmane.comp.python.tutor/36068/focus=36069
> http://article.gmane.org/gmane.comp.python.tutor/36105/match=generator

Here is another good article about what happens behind the scenes of a 
for loop:
http://online.effbot.org/2006_11_01_archive.htm#for

Kent



More information about the Tutor mailing list