[Tutor] iter class

Keith Winston keithwins at gmail.com
Thu Jan 23 05:57:51 CET 2014


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).

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.

-- 
Keith


More information about the Tutor mailing list