How to stop iteration with __iter__() ?

John Machin sjmachin at lexicon.net
Tue Aug 19 19:11:43 EDT 2008


On Aug 20, 5:06 am, Terry Reedy <tjre... at udel.edu> wrote:
> In your case, the standard Python idiom, as Jon said, is
>
> it = iter(iterable)
> next(it) # 2.6, 3.0
> for for item in iterable:
>    f(item)

or, perhaps, for completeness/paranoia/whatever:

it = iter(iterable)
try:
   headings = it.next() # < 2.5
except StopIteration:
   # code to handle empty <iterable>
for item etc etc

> The alternative is a flag variable and test
>
> first = True
> for for item in iterable:
>    if first:
>      first = False
>    else:
>      f(item)
>
> This takes two more lines and does an unnecessary test for every line
> after the first.  But this approach might be useful if, for instance,
> you needed to skip every other line (put 'first = True' after f(item)).

and change its name from 'first' to something more meaningful ;-)

Cheers,
John



More information about the Python-list mailing list