Categories
cycle indexing list python python-3.x

Is there a way to cycle through indexes

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:

Code:

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

Results:

1