You have probably had the chance to iterate through a list of elements in one way or another, or through elements of a set, or a dictionary. We can go through a list, a set, or a dictionary and access their elements because they are iterable objects.

An iterator is an object that contains a countable number of objects. This means that you can iterate through elements that an iterator contains.

We can actually build our own Iterator objects quite easily. All we have to do is implement two methods __iter__() and __next()__ and we are good to go.

Let us see this with an example where we are building a class from which we can get iterator objects.

 class OddNumbers:
     def __iter__(self):
         self.a = 1
         return self
 ​
     def __next__(self):
         x = self.a
         self.a += 2
         return x

In the first method __iter__(), we are defining the attributes that an object of this class will contain.

In the second method, __next()__, we are implementing the way we want new items to be returned from this iterator. Since we want to get a list of odd numbers, we want to get the current element of the number and increase it by 2.

Here is an example to illustrate this.

We need to use the iter() method to get the iterator object and then traverse through it.

 odd_numbers_object = OddNumbers()
 iterator = iter(odd_numbers_object)
 ​
 print(next(iterator))  # 1
 print(next(iterator))  # 3
 print(next(iterator))  # 5

That’s basically it.

I hope you find this useful.