Nested iteration?

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Apr 23 12:05:13 EDT 2013


On 23 April 2013 16:40, Roy Smith <roy at panix.com> wrote:
> In reviewing somebody else's code today, I found the following
> construct (eliding some details):
>
>     f = open(filename)
>     for line in f:
>         if re.search(pattern1, line):
>             outer_line = f.next()
>             for inner_line in f:
>                 if re.search(pattern2, inner_line):
>                     inner_line = f.next()
>
> Somewhat to my surprise, the code worked.  I didn't know it was legal
> to do nested iterations over the same iterable (not to mention mixing
> calls to next() with for-loops).  Is this guaranteed to work in all
> situations?

For Python 3 you'd need next(f) instead of f.next(). Otherwise, yes,
this works just fine with any non-restarting iterator (i.e. so that
__iter__ just returns self rather than a new iterator).

I recently posted in another thread about why it's a bad idea to call
next() without catching StopIteration though. I wouldn't accept the
code above for that reason.


Oscar



More information about the Python-list mailing list