How to stop iteration with __iter__() ?

MRAB google at mrabarnett.plus.com
Wed Aug 20 05:56:07 EDT 2008


On Aug 20, 12:11 am, John Machin <sjmac... at lexicon.net> wrote:
> 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
>
I think it needs to be:

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

because you don't want to iterate over the remainder if it has already
stopped yielding! :-)

> > 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