Next / Previous / Contents / TCC Help System / NM Tech homepage

18. Recent features

The Python language is in active development. Sections below describe some major new features since version 2.0.

18.1. Iterators

New features in Python 2.2 generalize the process of visiting the elements of a sequence.

These features all affect the way for statements work. In the general case, a for statement looks like this:

for v in S:

where the block B is executed once for each element of the sequence S, with some destination v set to each element of S in turn.

An iterator is a new concept that generalizes the sequence S so that you can use objects other than regular sequence types like lists and tuples. An iterator is an object that knows how to visit a sequence of values.

The way for statements actually work now is that it calls the built-function iter(S) to convert the sequence into an iterator that knows how to visit the elements of S. Calling iter(S) where S is a list or tuple returns an iterator that visits each element of the list or tuple in turn, with index values 0, 1, 2, ....

Any object with the special .__getitem__() method can be used as the sequence in a for statement. Values 0, 1, ... are used for the index, and the for statement terminates when .__getitem__() raises IndexError.

Objects may also have an .__iter__() method, which supersedes the .__getitem__() method in for statements. This method implements the iter() function for the class, and returns an iterator for the instance.

An iterator must be an object with a .next() method that takes no arguments and returns the next element in sequence. This method should raise the special exception StopIteration to signify that there are no more elements.