frisbee
frisbee

Reputation: 103

resetting the start value of for loop in Range(start, end) in python

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

Upvotes: 0

Views: 5190

Answers (2)

Andrey Bondar
Andrey Bondar

Reputation: 130

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

Upvotes: 2

Laurent H.
Laurent H.

Reputation: 6526

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 ...

Upvotes: 1

Related Questions