0

I am trying to create a iterable class but have been banging my head on a wall so to speak, getting "object is not iterable". This is my code:

class myiterable:
    def __init__(self, somelist):
        self.i = 0
        self.l = somelist

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < len(self.l):
            self.i = self.i + 1
            return self.l[self.i-1]
        else:
            raise StopIteration



for i in myiterable([1, 2, 3, 4, 5]):
    print(i)

What's wrong? I have also tried next(self) in lieu of __next__(self) to no avail!

Tarik
  • 10,810
  • 2
  • 26
  • 40
  • 2
    Look at your indentation. See anything wrong here? Please do correct it if this is not what you meant. If you don't see anything wrong, look harder and that's your problem. – Martijn Pieters Aug 29 '13 at 08:46
  • 4
    `++self.i` is **not** python syntax, btw. Use `self.i += 1`. Your version will just lead to an infinite loop instead. – Martijn Pieters Aug 29 '13 at 08:47
  • Fixed code and posted new version. Same problem. – Tarik Aug 29 '13 at 08:50
  • 1
    If this is the fixed version then you just found your problem. `__iter__` and `__next__` are not methods on `myiterable`; they are nested functions inside `__init__`. – Martijn Pieters Aug 29 '13 at 08:51
  • @MartijnPieters Thanks for pointing out my other mistakes. – Tarik Aug 29 '13 at 08:54

2 Answers2

5

There are several problems with your code:

  • indentation
  • if you are on python 2, you should have defined next() method instead of __next__() (leave it as is if on python 3)
  • ++self.i should be replaced with self.i += 1
  • self.l[i-1] should be replaced with self.l[self.i-1]

class myiterable:
    def __init__(self, somelist):
        self.i = 0
        self.l = somelist

    def __iter__(self):
        return self

    def next(self):
        if self.i < len(self.l):
            self.i += 1
            return self.l[self.i-1]
        else:
            raise StopIteration


for i in myiterable([1, 2, 3, 4, 5]):
    print(i)

prints:

1
2
3
4
5
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
3

If you just copied your code, then it should be because of bad indent. Pull __iter__ and __next__ to same indent as __init__.

TieDad
  • 9,143
  • 5
  • 32
  • 58