Frage

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
War es hilfreich?

Lösung

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top