Python Iterators :

Python Iterators :

An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

Create an Iterator :

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you do some initializing when the object is being created.

The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself and the __next__() method also allows you to do operations, and must return the next item in the sequence.

Example :

  1. #Create an iterator that returns numbers (1 to 10 - each sequence will increase)
  2. class MyNumbers:
  3. def __iter__(self):
  4. self.y = 1
  5. return self
  6. def __next__(self):
  7. x = self.y
  8. self.y += 1
  9. return x
  10. myclass = OurNumbers()
  11. myite = iter(myclass)
  12. print(next(myite))
  13. print(next(myite))
  14. print(next(myite))
  15. print(next(myite))
  16. print(next(myite))
  17. print(next(myite))
  18. print(next(myite))
  19. print(next(myite))
  20. print(next(myite))
  21. print(next(myite))
  22. input()

Output :

python Iterator example

StopIteration :

To prevent the iteration to go on forever, we can use the StopIteration statement.

Example :

  1. #Stop after 20 iterations
  2. class MyNumbers:
  3. def __iter__(self):
  4. self.y = 1
  5. return self
  6. def __next__(self):
  7. if self.y <= 20:
  8. x = self.y
  9. self.y += 1
  10. return x
  11. else:
  12. raise StopIteration
  13. myclass = OurNumbers()
  14. myite = iter(myclass)
  15. for x in myite:
  16. print(x)
  17. input()

Output :

python StopIteration example

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes