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!

5
  • 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. Commented Aug 29, 2013 at 8:46
  • 4
    ++self.i is not python syntax, btw. Use self.i += 1. Your version will just lead to an infinite loop instead. Commented Aug 29, 2013 at 8:47
  • Fixed code and posted new version. Same problem. Commented Aug 29, 2013 at 8: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__. Commented Aug 29, 2013 at 8:51
  • @MartijnPieters Thanks for pointing out my other mistakes. Commented Aug 29, 2013 at 8:54

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Python 3 uses .__next__(), not .next().
The OP uses print(i), you can assume Python 3 here.
3

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

1 Comment

My God! I cannot believe I fell for such a stupid mistake! Thanks man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.