Search code examples
pythonlistcycle

How can the indexation of a list be made cyclic in python?


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

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