9
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]?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Aditya
  • 144
  • 2
  • 13

3 Answers3

9

You can you modulo math like:

Code:

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

Results:

1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
3

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.

Rockybilly
  • 2,938
  • 1
  • 13
  • 38
3

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.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73