Home > AI > Language > Python >

Iterator

An iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__()

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

Example 1:

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

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

Example 2: Build custom an Iterator

class PowTwo:

    def __init__(self, max=0):
        self.max = max

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration



numbers = PowTwo(3)
i = iter(numbers) # iterator

print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))

Leave a Reply