w1coding.comAll tutorials

Python Iterators

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

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.