The Python language is in active development. Sections below describe some major new features since version 2.0.
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:
forvinS:B
where the block is executed
once for each element of the sequence
B, with
some destination
S set
to each element of
v in turn.S
An iterator is a new concept that generalizes the
sequence
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.S
The way for statements
actually work now is that it calls the built-function
iter(
to convert the sequence into an iterator that knows how
to visit the elements of S). Calling
Siter(
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, ....S
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.