Closely related to Python's concept of sequences is the concept of an iterator:
For a given sequence
, an iteratorSis essentially a set of instructions for producing the elements ofIas a sequence of zero or more values.S
To produce an iterator over some sequence , use this function:
S
iter(S)
The result of this function is an “iterator
object” that can be used in a for statement.
>>> continents = ('AF', 'AS', 'EU', 'AU', 'AN', 'SA', 'NA')
>>> worldWalker = iter(continents)
>>> type(worldWalker)
<type 'tupleiterator'>
>>> for landMass in worldWalker:
... print "Visit {0}.".format(landMass,)
...
Visit AF. Visit AS. Visit EU. Visit AU. Visit AN. Visit SA. Visit NA.
All iterators have a .next() method
that you can call to get the next element in the
sequence. This method takes no arguments. It
returns the next element in the sequence, if any.
When there are no more elements, it raises a StopIteration exception.
>>> trafficSignal = [ 'green', 'yellow', 'red' ] >>> signalCycle = iter(trafficSignal) >>> type(signalCycle) <type 'listiterator'> >>> signalCycle.next() 'green' >>> signalCycle.next() 'yellow' >>> signalCycle.next() 'red' >>> signalCycle.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
Once an iterator is exhausted, it will continue to raise
StopIteration indefinitely.
You can also use an iterator as the right-hand
operand of the “in”
operator.
>>> signalCycle = iter(trafficSignal) >>> 'red' in signalCycle True