Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterability in Python

I am trying to understand Iterability in Python.

As I understand, __iter__() should return an object that has next() method defined which must return a value or raise StopIteration exception. Thus I wrote this class which satisfies both these conditions.

But it doesn't seem to work. What is wrong?

class Iterator:
    def __init__(self):
        self.i = 1

    def __iter__(self):
        return self

    def next(self):
        if self.i < 5:
            return self.i
        else:
            raise StopIteration

if __name__ == __main__:
    ai = Iterator()
    b  = [i for i in ai]
    print b
like image 659
lprsd Avatar asked Dec 02 '22 08:12

lprsd


1 Answers

Your Iterator class is correct. You just have a typo in this statement:

if __name__ ==' __main__':

There's a leading whitespace in the ' __main__' string. That's why your code is not executed at all.

like image 149
Haes Avatar answered Dec 16 '22 03:12

Haes