Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Nobody Newsgroups: comp.lang.python Subject: Re: Resetting the Range start in the middle of a loop Date: Sat, 24 Oct 2015 03:13:56 +0100 Organization: A noiseless patient Spider Lines: 54 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="152d4dee6f95183c956ee6fa63d7e69f"; logging-data="19423"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18b7G/mTR9qSi9FjMlMxDbk" User-Agent: Pan/0.14.2 (This is not a psychotic episode. It's a cleansing moment of clarity.) Cancel-Lock: sha1:9+Q7dlsFaaz5B9lr/V5XILTetbE= Xref: csiph.com comp.lang.python:97925 On Fri, 23 Oct 2015 08:42:53 -0700, bigred04bd3 wrote: > I am wanting to reset a Range start while a loop is running. here is what > I have: > > s = 1 > for i in range(s, 1000): > # do stuff > for r in range(i, 1000): > # do stuff > s = s + 100 #example > break > > > I've also tried to update the i as well, but it just continues on to the > next number as if it was never updated. You either need a while loop or a custom iterator. E.g.: class Iterator(object): def __init__(self, start, end): self.cur = start self.end = end def set(self, cur): self.cur = cur def __iter__(self): return self def next(self): if self.cur >= self.end: raise StopIteration i = self.cur self.cur += 1 return i So then you can do e.g.: it = Iterator(s, 1000) for i in it: # do stuff for r in range(i, 1000): # do stuff s = s + 100 #example it.set(s) break Unless you need to do this sort of thing a lot, use a while loop. A "for" loop is used when the set of values is known in advance. C's "for" loops (since copied by other C-like languages) are "while" loops in disguise. Python's "for" loops are actually "for" loops.