Skip to content
Advertisement

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

I’m looking for some code improvement, or a pre-built version of what I’ve implemented myself as I think there might be, or should be, a cleaner way to achieve what I want.

I’m writing a piece of software to convert guitar tabs into classical notation, I need to convert the number on a tab to it’s corresponding note and it would be useful for building a list of each strings note from the starting string.

I have a list of notes, (a – g#) and a list of frets (0, 21).

Notes[fret] works fine for the first eleven notes but after that I obviously get an out of index error.

The code I have to get around this is here:

notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
note = 21
while note >= len(notes):
    note -= 11
    try:
        print notes[note]
    except:
        continue

It works but it seems a little long, is there a better way to do this?

Advertisement

Answer

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#
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement