Question

If we have a list:

myList = [1,2,3,4,5]

What is the pythonic way of making the indexation of a list cyclic? Meaning i can never get indexError. And i need the indexation, therefore i can't use cycle with next
For example:

>>>myList[6]
2
>>>myList[-6]
5
Was it helpful?

Solution

You can use modulus operator, like this

myList = [1, 2, 3, 4, 5]
print myList[6  % len(myList)]
# 2
print myList[-6 % len(myList)]
# 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top