Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I want to infinitely iterate through the list from 0 to the end, but in the 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 0 to the end…

a = [ 0, 1, 2 ]
offset = 0
rotate = 0
while True:
    b = a[rotate]
    print(b)
    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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

and so on.

>Solution :

Try this:

a = [0, 1, 2]

while True:
    print(a)
    a.append(a[0])
    a.pop(0)

Output:

[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
...

EDIT (suggested by Tomerikoo):
To remove the brackets use

a = [0, 1, 2]

while True:
    print(*a, sep=', ')
    a.append(a[0])
    a.pop(0)

Output:

0, 1, 2
1, 2, 0
2, 0, 1
0, 1, 2
1, 2, 0
2, 0, 1
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading