Nested iteration?

Roy Smith roy at panix.com
Tue Apr 23 11:40:31 EDT 2013


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?



More information about the Python-list mailing list