Labs ICT
Pro Login

Iterators

Basic Iterator with iter() and next()

An iterator is an object that can be looped over. Use iter() to get an iterator and next() to get each item. StopIteration is raised when there are no more items.

nums = [10, 20, 30]
it = iter(nums)
print(next(it))
print(next(it))
print(next(it))
Try it Yourself →

Custom Iterator Class

Implement __iter__() and __next__() to make your own iterator. The __iter__() method returns the iterator object itself.

class CountDown:
    def __init__(self, start):
        self.n = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

for num in CountDown(5):
    print(num)
Try it Yourself →