What Is Iterator Object

This section provides a quick introduction on iterator object, which is an object with a required instance method to return the next item from a collection.

What Is Iterator Object - An iterator object is an object that supports a required instance method, iterator.__next__(), to return the next item from a collection. If there is no more item to return, iterator.__next__() should raise the "StopIteration" error.

By the way, the required method is called object.next() in Python 2.

Once you have an iterator object created, you can call the built-in method next(iterator) to retrieve the next item. next(iterator) will call iterator.__next__() for you. So the following statements are equivalent:

next(iterator)        # preferred way to retrieve the next item

iterator.__next__()   # used in Python 3
iterator.next()       # used in Python 2

The main purpose of using an iterator object is to iterate over all items in a collection by calling the next(iterator) method repeatedly in loop statements. However there is no easy way to test the of the collection, so you need to a "try" statement block to catch the "StopIteration" error to end the loop

try:
   while True:
      item = next(iterator)
      ...
except StopIteration:
   pass

The tutorial example code, iterator_test.py, listed below shows you how to create a class with the required method defined, and call the class constructor to create an iterator object. The code also include two ways to use the iterator object.

#  iterator_test.py
#- Copyright 2011 (c) HerongYang.com. All Rights Reserved.
#

# define a class
class top3:
   items = ['C', 'Java', 'JavaScript']

   def __init__(self):
      self.i = 0

   # define the required method by the iterator interface for Python 3
   def __next__(self):
      if self.i < 3:
         self.i += 1
         return top3.items[self.i-1]
      else:
         raise StopIteration()

   # define the required method by the iterator interface for Python 2
   def next(self):
      return self.__next__()

# create an iterator object and retrieve its items in a "while" loop
iter = top3()
try:
   while True:
      item = next(iter)
      print(item)
except StopIteration:
   print("End of collection reached...")

# create an iterator object and retrieve its items without any loops
iter = top3()
try:
   print(next(iter))
   print(next(iter))
   print(next(iter))
   print(next(iter))
   print(next(iter))
   print(next(iter))
except StopIteration:
   print("End of collection reached...")

If you run this sample code, you should get:

herong> python iterator_test.py

C
Java
JavaScript
End of collection reached...

C
Java
JavaScript
End of collection reached...

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

 Statements - Execution Units

 Function Statement and Function Call

Iterators and Generators

What Is Iterator Object

 What Is Iterable Object

 Iterable Objects of Built-in Data Types

 What Is Generator Iterator

 What Is Generator Expression

 What Is Filtered Generator Expression

 What Is Double-Generator Expression

 List, Set and Dictionary Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB