Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Iterators and the Python for statement

The Python compiler automatically generates code to use an iterator when the for statement is used. Thus, given an object c that is an instance of a concrete class SomeContainer derived from the abstract Container base class, we can use the for statement to enumerate the objects in the container as follows:

c = new SomeContainer();
# ...
for obj in c:
    print obj

One of the advantages of using an iterator object that is separate from the container is that it is possible to have more than one iterator associated with a given container. For example, consider the following code fragment:

c = SomeContainer()
# ...
for obj1 in c:
    for obj2 in c:
	if obj1 == obj2:
	    print obj1, obj2
This code implicitly uses two distinct iterators, one for each for loop. This code compares all ordered-pairs of objects in the container c and prints out those which are equal.

next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.