The 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
situations.
-
iter
(
iterable
)
→ iterator
-
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 set
s, it
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
for
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.
>>>
seq=range(10)
>>>
seqIter= iter(seq)
>>>
seqIter.next()
0
>>>
seqIter.next()
1
>>>
for v in seqIter:
... print v
2
3
4
5
6
7
8
9
|
We create a sequence, seq . Any iterable
object would work here; any sequence, set ,
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
for
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
for
statement. The
for
statement repeatedly calls
the next method and executes its suite of
statements.
|