Question

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!

Was it helpful?

Solution 2

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top