iterators

Python Iterators

Python Iterators

An iterator is an object in Python that can be iterated (looped) upon. They implement two methods: __iter__() and __next__().

Creating an Iterator

You can create an iterator by defining a class that implements these two methods:

      
        class MyIterator:
            def __init__(self, start, end):
                self.current = start
                self.end = end

            def __iter__(self):
                return self

            def __next__(self):
                if self.current > self.end:
                    raise StopIteration
                self.current += 1
                return self.current - 1

        iter_obj = MyIterator(1, 5)
        for num in iter_obj:
            print(num)
      
    

In the above code, MyIterator is a custom iterator that loops from start to end.

Activity

Try It Yourself!

Create an iterator class that generates a sequence of even numbers between a given range.

Quick Quiz

Quick Quiz

  1. What are the two methods an iterator must implement?
  2. What is the purpose of the StopIteration exception?

Answers: An iterator must implement __iter__() and __next__(). StopIteration is raised to indicate that there are no more items to return from the iterator.