Search code examples
pythonpython-3.xlistcircular-list

Make array repeat when got IndexError


I want an array to loop when the code throws the IndexError. Here is the Example:

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

a[x] -> output
0 -> 1
1 -> 2
...
4 -> 5
after except IndexError
5 -> 1
6 -> 2
...
9 -> 5
10 -> IndexError (Should be 1)

My code works but when pos > 9 it still throws the IndexError.

pos = 5
try:
    a = [1, 2, 3, 4, 5]
    print(a[pos])
except IndexError:
    print(a[pos - len(a)])

Solution

  • If you want a circular iterator, use itertools.cycle. If you just want circular behaviour when indexing, you can use modulo-based indexing.

    In [20]: a = [1, 2, 3, 4, 5]
    
    In [21]: pos = 9
    
    In [22]: a[pos % len(a)]
    Out[22]: 5