Wrapping around on a list when list index is out of range

Another options is to use itertools.cycle

>>> import itertools
>>> notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]

>>> frets = range(21)
>>> for note, fret in itertools.izip(itertools.cycle(notes), frets):
        print ("[%s, %d]" %(note, fret))

[a, 0]
[a#, 1]
[b, 2]
[c, 3]
[c#, 4]
[d, 5]
[e, 6]
[f, 7]
[f#, 8]
[g, 9]
[g#, 10]
[a, 11]
[a#, 12]
[b, 13]
[c, 14]
[c#, 15]
[d, 16]
[e, 17]
[f, 18]
[f#, 19]
[g, 20]

Use the % operator to produce a modulus:

notes[note % len(notes)]

Demo:

>>> notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
>>> note = 21
>>> notes[note % len(notes)]
'g#'

or in a loop:

>>> for note in range(22):
...     print notes[note % len(notes)],
... 
a a# b c c# d e f f# g g# a a# b c c# d e f f# g g#

Use the modulo operator:

In [3]: notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]

In [4]: len(notes)
Out[4]: 11

In [5]: note = 11

In [6]: notes[note]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-707e7e351463> in <module>()
----> 1 notes[note]

IndexError: list index out of range

In [7]: notes[note%len(notes)]
Out[7]: 'a'

In [8]: notes[note-11]
Out[8]: 'a'

Tags:

Python

List