[Tutor] iter class

Devin Jeanpierre jeanpierreda at gmail.com
Thu Jan 23 06:21:05 CET 2014


On Wed, Jan 22, 2014 at 8:57 PM, Keith Winston <keithwins at gmail.com> wrote:
> I'm working my way through some of the examples in
>
> http://ivory.idyll.org/articles/advanced-swc/#list-comprehensions
>
> And tried this one:
>
>>>> class MyTrickyIter:
> ...   def __init__(self, thelist):
> ...      self.thelist = thelist
> ...      self.index = -1
> ...
> ...   def __iter__(self):
> ...      return self
> ...
> ...   def next(self):
> ...      self.index += 1
> ...      if self.index < len(self.thelist):
> ...         return self.thelist[self.index]
> ...      raise StopIteration
>
> FYI, this is supposed to be an example of how NOT to do an iterator,
> because of the way it handles thelist (which is supposed to be an
> iteratable construct, like a list, if I'm not confused).

thelist is more like a sequence, meaning you can use myseq[n] for every value of
n between and including 0 and len(myseq) -1. (Although, sequences
usually have other things, too.) An iterable is anything you can loop
over with a for loop.

This is a perfectly reasonable iterator, but iterators are always
tricky when used as an iterable -- you can't do a nested loop over a
single iterator, because the iterator used for both loops will be the
same iterator, and keep the same state.

> Anyway, my efforts to recreate the following example:
>
>>>> mi = MyTrickyIter(['a', 'b'])
>>>> for i in mi:
> ...   for j in mi:
> ...      print i, j
>
> which should result in
>
> a b
>
> instead results in
>
> Traceback (most recent call last):
>   File "<pyshell#57>", line 1, in <module>
>     for i in mi:
> TypeError: iter() returned non-iterator of type 'MyTrickyIter'
>
> I'm sort of wondering if there's a Py2 vs. Py3 issue here, but I don't see it.

in Python 3, it should be __next__, not next.

I'd suggest staying away from any old blog posts and articles, unless
you'd care to learn Python 2.x instead of 3.x. ;)

-- Devin


More information about the Tutor mailing list