Path: csiph.com!usenet.pasdenom.info!aioe.org!news.stack.nl!newsfeed.xs4all.nl!newsfeed4.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.010 X-Spam-Evidence: '*H*': 0.98; '*S*': 0.00; 'nested': 0.07; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'worked.': 0.09; 'def': 0.12; 'iterable': 0.16; 'iterator': 0.16; 'loops': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-ipconnect.de': 0.16; 'roy': 0.16; 'wrote:': 0.18; '(not': 0.18; "python's": 0.19; 'header:User-Agent:1': 0.23; 'mention': 0.26; 'header:X-Complaints-To:1': 0.27; 'code': 0.31; 'consequence': 0.31; 'allows': 0.31; 'file': 0.32; 'class': 0.32; 'skip:_ 10': 0.34; 'but': 0.35; "didn't": 0.36; 'subject:?': 0.36; 'sometimes': 0.38; 'depends': 0.38; 'somebody': 0.38; 'to:addr :python-list': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'today,': 0.61; 'smith': 0.68; 'legal': 0.71; 'guaranteed': 0.75; 'calls,': 0.84; "else's": 0.84; 'burn': 0.91; 'state.': 0.95 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: Nested iteration? Date: Tue, 23 Apr 2013 18:15:42 +0200 Organization: None References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p50849f5f.dip0.t-ipconnect.de User-Agent: KNode/4.7.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 31 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1366733742 news.xs4all.nl 2311 [2001:888:2000:d::a6]:34316 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:44195 Roy Smith 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? That depends on what you mean by "all". A well-behaved iterator like Python's file object allows mixing of for loops and next(...) calls, but stupid people who deserve to burn in hell sometimes do class MyIterable: def __iter__(self): reset_internal_counter() return self with the consequence that every for loop implicitly resets the iterator's state.