The following section uses file to illustrate what is an iterator.
open file objects have a method called readline.
It reads one line of text from a file at a time-each time we call the readline method, we advance to the next line.
At the end of the file, an empty string is returned, which we can detect to break out of the loop:
f = open('main.py') # Read a four-line script file in this directory print( f.readline() ) # readline loads one line on each call # from w ww.ja v a2 s.c o m print( f.readline() ) print( f.readline() ) print( f.readline() ) # Last lines may have a \n or not print( f.readline() ) # Returns empty string at end-of-file
files also have a method named __next__ in 3.X (next in 2.X) that has the same effect.
It returns the next line from a file each time it is called.
__next__ raises a built-in StopIteration exception at end-of-file instead of returning an empty string:
f = open('main.py') print( f.__next__() ) print( f.__next__() ) print( f.__next__() ) print( f.__next__() ) print( f.__next__() )
This interface is most of what we call the iteration protocol in Python.
Any object with a __next__ method to advance to a next result, which raises StopIteration at the end of the series of results, is considered an iterator in Python.
Any such object may be stepped through with a for loop or other iteration tool.
All iteration tools work internally by calling __next__ on each iteration and catching the StopIteration exception to determine when to exit.