Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through list infinitely with +1 offset each loop

Tags:

python

I want to infinitely iterate through the list from 0 to the end, but in the next loop I want to start at 1 to the end plus 0, and the next loop would start at 2 to the end plus 0, 1, up to the last item where it would start again at 0 and go to the end.

Here is my code:

a = [ 0, 1, 2 ]
offset = 0
rotate = 0

while True:
    print(a[rotate])
    offset += 1
    rotate += 1
    if offset >= len(a):
        offset = 0
        rotate += 1
    if rotate >= len(a):
        rotate = 0

This is the solution I came up with so far. It's far from perfect.

The result that I want is:

0, 1, 2 # first iteration
1, 2, 0 # second iteration
2, 0, 1 # third iteration
0, 1, 2 # fourth iteration

and so on.

like image 943
Scrampus Avatar asked Sep 05 '25 09:09

Scrampus


1 Answers

You can use a deque which has a built-in and efficient rotate function (~O(1)):

>>> d = deque([0,1,2])
>>> for _ in range(10):
...     print(*d)
...     d.rotate(-1)  # negative -> rotate to the left
...
0 1 2
1 2 0
2 0 1
0 1 2
1 2 0
2 0 1
0 1 2
1 2 0
2 0 1
0 1 2
like image 78
GACy20 Avatar answered Sep 08 '25 10:09

GACy20