• Python

Command Palette

Search for a command to run...

Native Functions
  • Python Abs Function
  • Python Any All Functions
  • Python Zip Function
  • Python Sum Function
  • Python Filter Function
  • Python Max Min Functions
  • Python Map Function
  • Python Round Function
  • Python Sorted Function
Data Types
  • Python Integers
  • Python Floats
  • Python Complex Numbers
  • Python List Type
  • Python Tuple Type
  • Python String Type
  • Python Range Type
Collections.abc Module
  • Python Containers
  • Python Hashable
  • Python Iterable
  • Python Iterators
  • Python Sequence
  • Python Mutable Sequence

Create an Account

FREE

Join our community to access more courses.

Create Account

On this page

What Is an Iterator?The and MethodsUsing collections.abc.IteratorKey Takeaways
      • Blog

      Python Iterators

      What Is an Iterator?

      An iterator is an object that represents a stream of data. It implements the iterator protocol, which consists of two methods: __iter__() and __next__().

      • The __iter__() method returns the iterator object itself.
      • The __next__() method returns the next item from the stream. If there are no more items, it should raise a StopIteration exception.

      Iterators are fundamental to how for loops and other iteration constructs work in Python.

      The collections.abc.Iterator abstract base class (ABC) defines this minimal interface for iterator types.

      The iter and next Methods

      To be recognized as an iterator, a class must implement both the __iter__() and __next__() methods:

      from collections.abc import Iterator
      
      class MyIterator(Iterator):
          def __init__(self, data):
              self.data = data
              self.index = 0
      
          def __iter__(self):
              return self
      
          def __next__(self):
              if self.index < len(self.data):
                  value = self.data[self.index]
                  self.index += 1
                  return value
              else:
                  raise StopIteration
      
      # Example usage:
      my_list = [10, 20, 30]
      my_iter = MyIterator(my_list)
      
      for item in my_iter:
          print(item) # 10, 20, 30
      
      # You can also manually iterate:
      my_iter_manual = MyIterator(my_list)
      print(next(my_iter_manual)) # 10
      print(next(my_iter_manual)) # 20
      

      Using collections.abc.Iterator

      You can check if a class or object is an iterator using isinstance or issubclass:

      from collections.abc import Iterator
      
      class AnotherIterator(Iterator):
          def __init__(self, start, end):
              self.current = start
              self.end = end
      
          def __iter__(self):
              return self
      
          def __next__ (self):
              if self.current < self.end:
                  value = self.current
                  self.current += 1
                  return value
              else:
                  raise StopIteration
      
      print(issubclass(AnotherIterator, Iterator)) # True
      print(isinstance(AnotherIterator(0, 5), Iterator)) # True
      
      # Built-in iterators also conform:
      list_iterator = iter([1, 2, 3])
      print(isinstance(list_iterator, Iterator)) # True
      

      It's generally recommended to inherit directly from collections.abc.Iterator (or other relevant ABCs) when designing your classes. This makes your code more explicit about its intended interface and can help static analysis tools. However, it's not strictly mandatory; Python's duck typing means that if your class implements the required __iter__() and __next__() methods, it will be recognized as an iterator, even without explicit inheritance from the ABC.

      Key Takeaways

      • Iterators are objects that produce data one item at a time.
      • They must implement both __iter__() (returning self) and __next__() (returning the next item or raising StopIteration).
      • The collections.abc.Iterator ABC provides a standard way to check for this protocol compliance.

      Continue Learning

      Python Variables

      Popular

      Getting Started: Understanding Variables in Python In programming, we often need to store informatio

      Python Sets

      For You

      Working with Unique Items: Understanding Sets in Python Imagine you have a list of items, and some i

      Python Functions Scope

      For You

      Where Variables Live: Understanding Scope In Python, not all variables are accessible from every par

      Personalized Recommendations

      Log in to get more relevant recommendations based on your reading history.