Is there a way to loop through a list from a specific index that wraps back to the front onwards?

Question:

Is there a way to loop through a list from a specific index that wraps back to the front?

Let’s imagine a list

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Is there a way to loop from 4 onwards, wrapping back to the front and continuing from there?

Ideally iterating through the original list as I need to modify the values.

Expected output:

4 5 6 7 8 9 0 1 2 3

Visualized example

Asked By: Alan

||

Answers:

There is. You can slice the list in two and iterate over them in the same loop like this:

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
idx = 4
for i in arr[idx:] + arr[:idx]:
    print(i)
Answered By: LTJ

If you want to use the iterator directly, then you can use

for x in arr[4:] + arr[:4]:
    # operations on x

I used the + for concatenation assuming it is a native Python List

Otherwise if you use indices:

for i in range(len(arr)):
    x = arr[(4 + i)%len(arr)]
    # operations on x
Answered By: PlainRavioli
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.