[Tutor] Iterators and Generators...
Karl Pflästerer
sigurd at 12move.de
Wed Aug 13 19:06:42 EDT 2003
On 13 Aug 2003, Marc Barry <- marc_barry at hotmail.com wrote:
> class list_iterator:
> def __init__(self, a_list):
> self.a_list = a_list
> def __iter__(self):
> return self
^^^^
here you should call your next method
> def next(self):
> for i in self.a_list:
> yield i
> raise StopItertion
^^
StopIteration
> a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])
> for i in a_list_iterator:
> print i
[...]
> Instead, I get something similar to the following:
> <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?
You never called your next() method (and you have a typo); I underlined
both in your example.
So the correct code would be:
class list_iterator:
def __init__(self, a_list):
self.a_list = a_list
def __iter__(self):
return self.next()
def next(self):
for i in self.a_list:
yield i
raise StopIteration
# Example in IPython
In [32]: a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])
In [33]: for i in a_list_iterator:
....: print i
....:
1
2
3
4
5
6
7
8
9
10
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list