Pythonic Circular List

You could use the modulo operator!

i = len(l) - 1
jIndex = (i - 1) % len(l)
kIndex = (i + 1) % len(l)

j = l[jIndex]
k = l[kIndex]

Or, to be less verbose:

k = l[(i + 1) % len(l)]

Leave a Comment