Nested iteration?

Chris Angelico rosuav at gmail.com
Tue Apr 23 12:21:25 EDT 2013


On Wed, Apr 24, 2013 at 1:40 AM, 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?

The definition of the for loop is sufficiently simple that this is
safe, with the caveat already mentioned (that __iter__ is just
returning self). And calling next() inside the loop will simply
terminate the loop if there's nothing there, so I'd not have a problem
with code like that - for instance, if I wanted to iterate over pairs
of lines, I'd happily do this:

for line1 in f:
  line2=next(f)
  print(line2)
  print(line1)

That'll happily swap pairs, ignoring any stray line at the end of the
file. Why bother catching StopIteration just to break?

ChrisA



More information about the Python-list mailing list