iter function can be used to acquire an
iterator object associated with a container like a sequence,
set, file or
dict. We can
then manipulate this iterator explicitly to handle some common
Returns the iterator from an object. This iterator interacts
with built-in types in obvious ways. For sequences this will
return each element in order. For
will return each element in no particular order. For dictionaries,
it will return the keys in no particular order. For files, it will
return each line in order.
Gettimg an explicit iterator — outside a
statement — is very handy for dealing with data structures (like files)
which have a head-body structure. In this case, there are one or more
elements (the head) which are processed one way and the remaining
elements (the body) which are processed another way.
We'll return to this in detail in Chapter 19, Files
For now, here's a small example.
for v in seqIter:
... print v
We create a sequence,
seq. Any iterable
object would work here; any sequence,
dict or file.
We create the iterator for this sequence, and assign it to
seqIter. This object has a
next method which is used by the
statement. We can call this explicitly to
get past the heading items in the sequence.
Here, we call
next explicitly to
yield the first two elements of the iterator.
Here, we provide the iterator to the
statement repeatedly calls
next method and executes its suite of