[Tutor] Iterators and Generators...

Marc Barry marc_barry at hotmail.com
Wed Aug 13 10:59:29 EDT 2003


Dear All:

I have a class which is an iterator, but I can't figure out why it is not 
working.  I have included a pointless example to illutsrate what is 
happening.  I have created a class called list_iterator that implements the 
iterator protocol over a list.  I know that that this is already done for 
lists, but it shows the problem I am having.  Here is the Python code:

#-----

class list_iterator:

	def __init__(self, a_list):
		self.a_list = a_list

	def __iter__(self):
		return self

	def next(self):
		for i in self.a_list:
			yield i
		raise StopItertion

a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])

for i in a_list_iterator:
	print i

#-----

When I run the above, I expected the following output:

1
2
3
4
5
6
7
8
9
10

Instead, I get something similar to the following:

<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
...  Well you get the point, it just loops forever.  Also, my yeild 
statement seems to be retruning a generator object instead of the number.  
Also, it never reaches the 'raise' statement.  Obviously, there is a flaw in 
my understanding of how to use a generator and the iterator protocol.  Can 
anyone clear this up for me?

Regards,

Marc

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online  
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963




More information about the Tutor mailing list