On Tue, Apr 23, 2013 at 9:40 AM, Roy Smith <r...@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?

Yes, although the results will be different depending on whether the
iterable stores its iteration state on itself (like a file object) or
in the iterator (like a list).  In the latter case, you would simply
have two independent simultaneous iterations of the same object.  You
can replicate the same effect in the latter case though by getting an
iterator from the object and explicitly looping over the same
iterator, like so:

i = iter(range(10))
for x in i:
    if x % 4 == 1:
        for y in i:
            if y % 4 == 3:
                print("%d + %d = %d" % (x, y, x+y))
                break
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to