Learning Python

19. Iterators

An interator is an object that contains a countable number of values and can be interated upon. Every object which implements the interator protocol with methods __iter__() and __next__().

19.1. The basics about iterators

#!/usr/bin/env python3

def main():
    mytuple = ("red", "big", "tasty")
    myit = iter(mytuple)

    print(next(myit))
    print(next(myit))
    print(next(myit))


if __name__ == "__main__":
    main()
red
big
tasty
#!/usr/bin/env python3

def main():
    mystr = "red"
    myit = iter(mystr)

    print(next(myit))
    print(next(myit))
    print(next(myit))


if __name__ == "__main__":
    main()
r
e
d
#!/usr/bin/env python3

def main():
    mytuple = ("red", "big", "tasty")

    for x in mytuple:
        print(x)


if __name__ == "__main__":
    main()
red
big
tasty
#!/usr/bin/env python3

def main():
    mystr = "red"

    for x in mystr:
        print(x)


if __name__ == "__main__":
    main()
r
e
d

19.2. Creating an iterator

#!/usr/bin/env python3

class MyCounter:
    def __iter__(self):
        self.i = 1
        return self

    def __next__(self):
        j = self.i
        self.i += 1
        return j


def main():
    mycounter = MyCounter()
    myit = iter(mycounter)

    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))


if __name__ == "__main__":
    main()
1
2
3
4
#!/usr/bin/env python3

class MyCounter:
    def __iter__(self):
        self.i = 1
        return self

    def __next__(self):
        if self.i <= 5:
            j = self.i
            self.i += 1
            return j
        else:
            raise StopIteration


def main():
    mycounter = MyCounter()
    myit = iter(mycounter)

    for x in myit:
        print(x)


if __name__ == "__main__":
    main()
1
2
3
4
5