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

Time:09-23

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related