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]
?
You can you modulo math like:
list1 = [1, 2, 3, 4]
print(list1[4 % len(list1)])
1
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With