Iterators (was: Re: [Tutor] text module)

Ibraheem Umaru-Mohammed iumarumo@eidosnet.co.uk
Sun, 1 Sep 2002 22:41:06 +0100


["Erik Price"="Erik"]
Erik >> On Saturday, August 31, 2002, at 08:56  PM, Ibraheem Umaru-Mohammed  
Erik >> wrote:
Erik >> 
Erik >> >A good article on iterators and generators is:
Erik >> >
Erik >> >	,---- [ url ]
Erik >> >	|  
Erik >> >http://www-106.ibm.com/developerworks/library/l- 
Erik >> >pycon.html?t=gr,lnxw10=PyIntro
Erik >> >	`----
Erik >> 
Erik >> Thanks Ibz, I will read that article.
Erik >> 
Erik >> >I haven't played much with iterators myself, nor simple generators,  
Erik >> >but the code
Erik >> >below might help, as it is an example that uses both the __iter__()  
Erik >> >and next() methods
Erik >> >required of user-defined classes that adhere to the iterator protocol.
Erik >> 
Erik >> "iterator protocol" makes me wonder if iterators are found in other  
Erik >> programming languages other than Python.  Obviously it wouldn't use the  
Erik >> double-underscore convention for the method to be subclassed, but is  
Erik >> this something that's found in C++, Java, or Obj-C (etc)?
Erik >> 

Iterators are definitely found in languages outside of python. From my
understanding of iterators, they are fundamentally extensions of the basic
looping constructs that operate on sequences (e.g for, while, repeat, until
etc), in order to operate on arbitrary objects that adhere to the protocol.

C++, Java, Smalltalk, Ruby for example have iterators...

Having played with Ruby recently, I have realised that the way Ruby objects do
iteration is very different to the way Python does it. In Ruby, you can quite
comfortable code away without having to use for, while or other looping
constructs because the objects themselves provide multiple iterable methods. 
For example, you could do this in Ruby:

	,-----[ Ruby loop ]
	| 0.upto(9) { |i| puts i }
	`---

which would be the equivalent of the following in python:

	¸------[ Python loop ]
	| for i in xrange(10):
	|   print i
	`---

You can see that the loop is passed "in" to the iterator object in
Ruby, whereas in Python, the iterator (xrange) passes objects to the looping
construct. In fact, I think the "each" method is equivalent to a "for"
loop in Ruby. For example,

	¸------[ Ruby loop ]
	| (0..9).each { |i| puts i }
	`---

Basically, the block passed to the iterator object in Ruby cannot end the
loop, only the iterator itself can end the loop. That is, there is no way to
break out of the iteration from within the block.  I think the same rule
applies in Python, in that iterators either return the next item when called
upon, or raise StopIteration when there are no more items to return. There is
no other clean way to break out of the iteration.

Hope that helps a little.

Kindest regards,

				--ibz.
-- 
				Ibraheem Umaru-Mohammed 
					"ibz"
			umarumohammed (at) btinternet (dot) com