0

I am avoiding using a while loop

In Java, I could do something like

for (int i = 0; i < 10; i++){
    if(.......) i = 0;
    //this will reset i to 0
}

In python this doesn't work:

j = 1
for i in range(j, n):
  if .....:
      j = 1

Is there a way i can reset the value of j.

NB: A while loop would solve the problem for me but I don't want to use it. Thanks

frisbee
  • 103
  • 1
  • 4
  • 1
    Using while loop would be simple here, why do you want to stick to for loop? I am not sure if it's possible with the for loop! – Tushar Aggarwal Jun 06 '18 at 11:37
  • You want a `for` loop within a `while` one no? `while True: for i in range(j, n): if ...: break` etc. – Chris_Rands Jun 06 '18 at 11:39
  • Why don't you want to use a while loop in this scenario? – Simeon Ikudabo Jun 06 '18 at 11:51
  • For example, you can simply regenerate the value of 1 (while 1 < 10) within a while loop in this case. Within a for loop, this obviously won't work since the value is generated at the beginning of the for loop within a specified range in Python. Differences between Java and Python. – Simeon Ikudabo Jun 06 '18 at 11:55

2 Answers2

1

In python3 range(..) returns range object, which is, even though it can't be exhausted like generators, is immutable and you can't rewind it.

May be you can look in Resetting generator object in Python - there is more information about it and some methods to bypass similar problems

In python2 range(..) returns list, but you still can't rewind it, because for i in range(..) still iterates over list sequentially and i is just a single value from list and overriding i value won't work, because list still references the same object, while you just changed where i variable points

  • 1
    This is wrong and misses the point, in Python 2 `range()` creates a list and in Python 3, `range()` creates a range object, which is not exhausted like a generator – Chris_Rands Jun 06 '18 at 11:51
1

To do so, you may create yourself your own generator in order to be able to modify its behavior, as follows for example:

class myRange:

    def restartFrom(self, start):
        self.start = start

    def get(self, start, end):
        self.start = start
        while self.start != end:
            yield self.start
            self.start += 1


myRange = myRange()

for i in myRange.get(1,10):
    print(i)
    # Restart from the beginning when 6 is reached
    if i == 6:
        myRange.restartFrom(0)

# It prints: 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 ...
Laurent H.
  • 6,316
  • 1
  • 18
  • 40