Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cycle through indexes [duplicate]

list1 = [1,2,3,4]

If I have list1 as shown above, the index of the last value is 3, but is there a way that if I say list1[4], it would become list1[0]?

like image 928
Aditya Avatar asked Mar 02 '18 02:03

Aditya


3 Answers

You can you modulo math like:

Code:

list1 = [1, 2, 3, 4]
print(list1[4 % len(list1)])

Results:

1
like image 84
Stephen Rauch Avatar answered Oct 16 '22 10:10

Stephen Rauch


In the situation you described, I myself use the method @StephenRauch suggested. But given that you added cycle as a tag, you might want to know there exists such a thing as itertools.cycle.

It returns an iterator for you to loop forever over an iterable in a cyclic manner. I don't know your original problem, but you might find it useful.

import itertools
for i in itertools.cycle([1, 2, 3]):
   # Do something
   # 1, 2, 3, 1, 2, 3, 1, 2, 3, ...

Be careful with the exit conditions though, you might find yourself in an endless loop.

like image 45
Rockybilly Avatar answered Oct 16 '22 09:10

Rockybilly


You could implement your own class that does this.

class CyclicList(list):
    def __getitem__(self, index):
        index = index % len(self) if isinstance(index, int) else index
        return super().__getitem__(index)

cyclic_list = CyclicList([1, 2, 3, 4])

cyclic_list[4] # 1

In particular this will preserve all other behaviours of list such as slicing.

like image 26
Olivier Melançon Avatar answered Oct 16 '22 09:10

Olivier Melançon