Home > Blockchain >  Python: Is there a way to loop through a list from a specific index that wraps back to the front onw
Python: Is there a way to loop through a list from a specific index that wraps back to the front onw

Time:09-22

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:

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)

CodePudding user response:

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

[x for x in arr[4:]   arr[:4]]

Otherwise if you use indices:

[arr[(4   i)%len(arr)] for i in range(len(arr))]

The examples produce a new list, but the idea is here

  • Related