Is there a way to loop index conversion

list1 = [1,2,3,4] 

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

+7
python list cycle indexing
source share
3 answers

You can modulo math:

The code:

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

Results:

 1 
+7
source share

In the described situation, I myself use the @StephenRauch method. But, given that you added cycle as a tag, you may know that there is such a thing as itertools.cycle .

It returns an iterator so that you can cycle through iterable cyclically. I do not know your original problem, but you may 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 exit conditions, but you may end up in an endless loop.

+3
source share

You can 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 list behaviors, such as slicing.

+3
source share

All Articles