Back and forth loop Python Back and forth loop Python python python

Back and forth loop Python


Use the chain method of itertools

import itertoolsfor i in range(0, infinity):    for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):        print(j) # (in my case 100 lines of code)

As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:

from itertools import cycle, chainfor i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):    ....


As well as the other answers you can use a bit of maths:

while(True):    for i in range(200):        if i > 100:            i = 200 - i


Here's yet another possibility:

while notConverged:    for i in xrange(-100, 101):        print 100 - abs(i)