bool (iterator)

Martin v. Loewis martin at v.loewis.de
Mon Aug 5 10:29:50 CEST 2002


Chirayu <thephoenix235 at gmx.net> writes:

> Is there a way for me to check if an iterator has "run out". I was
> hoping bool (iterator) would help but it always returns true.

That is what the else clause of a for loop is good for: It will be
only executed if the for loop ran to completion.

> iterObj = iter (obj)
> while 1:
>     for i in iterObj:
>        process i
>        break based on some condition
>     # continue until we've exhausted the iterator
>     if bool (iterObj)==0: break

You can write this as

iterObj = iter (obj)
while 1:
    for i in iterObj:
       process i
       break based on some condition
    else:
       # break out of while loop if the iterator is exhausted
       break

HTH,
Martin



More information about the Python-list mailing list