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__().

The basics about iterators

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("red", "big", "tasty")
 5    myit = iter(mytuple)
 6
 7    print(next(myit))
 8    print(next(myit))
 9    print(next(myit))
10
11
12if __name__ == "__main__":
13    main()

Output:

1red
2big
3tasty

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mystr = "red"
 5    myit = iter(mystr)
 6
 7    print(next(myit))
 8    print(next(myit))
 9    print(next(myit))
10
11
12if __name__ == "__main__":
13    main()

Output:

1r
2e
3d

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("red", "big", "tasty")
 5
 6    for x in mytuple:
 7        print(x)
 8
 9
10if __name__ == "__main__":
11    main()

Output:

1red
2big
3tasty

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mystr = "red"
 5
 6    for x in mystr:
 7        print(x)
 8
 9
10if __name__ == "__main__":
11    main()

Output:

1r
2e
3d

Creating an iterator

Example:

 1#!/usr/bin/env python3
 2
 3class MyCounter:
 4    def __iter__(self):
 5        self.i = 1
 6        return self
 7
 8    def __next__(self):
 9        j = self.i
10        self.i += 1
11        return j
12
13
14def main():
15    mycounter = MyCounter()
16    myit = iter(mycounter)
17
18    print(next(myit))
19    print(next(myit))
20    print(next(myit))
21    print(next(myit))
22
23
24if __name__ == "__main__":
25    main()

Output:

11
22
33
44

Example:

 1#!/usr/bin/env python3
 2
 3class MyCounter:
 4    def __iter__(self):
 5        self.i = 1
 6        return self
 7
 8    def __next__(self):
 9        if self.i <= 5:
10            j = self.i
11            self.i += 1
12            return j
13        else:
14            raise StopIteration
15
16
17def main():
18    mycounter = MyCounter()
19    myit = iter(mycounter)
20
21    for x in myit:
22        print(x)
23
24
25if __name__ == "__main__":
26    main()

Output:

11
22
33
44
55