On 23 April 2013 16:40, 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?
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 -- http://mail.python.org/mailman/listinfo/python-list