2

[python] 3.6
Hello, I was trying to iterate over a list with a for cycle, where I had to restart the cycle whenever a condition was confirmed. In C I would do:
for(i = 0; i < 10; i++){ if(list[i] == something) i = 0; }

Here I was trying to do this:

for x in listPrimes:
    if((num % x) == 0):
        num /= x # divide by the prime
        factorials.append(x)
        x = 2 # reset to the first prime in the list?

which doesn't work correctly. What are the ways to reset the for to a certain iteration of the list? Do I have to do the for in some other way?
Thanks for your time

user3483203
  • 50,081
  • 9
  • 65
  • 94
Miguel
  • 1,295
  • 12
  • 25
  • Possible duplicate of [python: restarting a loop](https://stackoverflow.com/questions/492860/python-restarting-a-loop) – Petr Javorik Jul 20 '18 at 16:15

4 Answers4

3

You could just use a while loop:

i = 0
while i < 10:
    print("do something", i)
    if random.random() < 0.2:
        print("reset")
        i = -1
    i += 1

Specific to your example:

i = 0
while i < len(listPrimes):
    x = listPrimes[i]
    if num % x == 0:
        num /= x
        factorials.append(x)
        i = -1
    i += 1
phngs
  • 476
  • 4
  • 9
  • Good answer, just had to change i = 0 inside the if to i = -1, or a continue because i will be incremented after. Thanks – Miguel Jul 20 '18 at 15:08
1

You can use a while loop similarly to your C code.

while i < 10: if list[i] == something: i = 0 i += 1

Josh Herzberg
  • 318
  • 1
  • 13
0

Use itertools.takewhile util

Here is a contrived example:

import itertools

li = [1,2,3,4,5]
for i in range(1, 6):
        print(list(itertools.takewhile(lambda x: x!=i, li)))
        print("new cycle")

Output:

[]
new cycle
[1]
new cycle
[1, 2]
new cycle
[1, 2, 3]
new cycle
[1, 2, 3, 4]
new cycle
dgumo
  • 1,838
  • 1
  • 14
  • 18
0

The while loop is the most elegant solution. Just for completeness you could wrap your list into custom generator and let this new iterable receive signal to reset the loop.

import time

def resetable_generator(li):
    while True:
        for item in li:
            reset = yield item
            if reset:
                break
        else:
            raise StopIteration


x = range(10)
sum = 0
r = resetable_generator(x)
for item in r:
    time.sleep(1)
    sum += item
    if item == 6:
        sum += r.send(True)
    print(sum)
Petr Javorik
  • 1,695
  • 19
  • 25