The standard way is:
it = iter(sequence)
for value in it:
print value
No need for the call to iter
here, it gets done implicitly in the loop:
for value in sequence:
print value
Ultimately, iter(obj)
returns obj.__iter__()
. This gets called implicitly when you start a for loop:
for elem in x:
implicitly does
for elem in iter(x):
Then, in the loop, python calls next
on the iterable returned by iter(obj)
to get the various elem
s until next
raises a Stopiteration
.
So your loop could be written as:
while True:
print record
try:
record = next(db)
except StopIteration:
break
Or more succinctly and idiomatically (as long as iter(db)
returns db
which is pretty typical):
for record in db:
print record
Generally, you can get the next value from an iterable using the next
function -- but the object needs to have a next
method (or __next__
on python3.x). If it's a sequence, you might need to call iter
on the object first in this case:
>>> obj = ['header','header2','record1']
>>> next(obj)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator
>>> iobj = iter(obj)
>>> next(iobj)
'header'
>>> next(iobj)
'header2'
>>> for x in iobj:
... print x
...
record1
Note that you can suppress a StopIteration
from being raised by next
by supplying a second argument to be returned instead of raising StopIteration
:
>>> next(iter([]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> next(iter([]),"Hello!")
'Hello!'
Seeing this, we find that you could also write your loop:
while record:
print record
record = next(db,False)
But the for
loop is definitely the cleanest way to do it for most objects.