IndexError: list index out of range in python, know the meaning, but don't understand why this happens
Question: I have the following code and I call the program writing:

    
    
    python new.py -s 13 -p 5
    

But then, in line 63 I get the following error. I know what it means but I
can't understan why.

    
    
    Traceback (most recent call last):
    File "new.py", line 63, in <module>
    rythm[i].append(rythm[last])
    IndexError: list index out of range
    

And there is the code. What I am trying to do is spread 0s equally among 1s.
The first input is the length of the string with the 0s and 1s, and the second
input is the numper of 1s. Thank you!

    
    
    import argparse
    
    
    p = argparse.ArgumentParser()
    p.add_argument("-pulses", help = "number of pulses", type = int)
    p.add_argument("-slots", help = "length of the rythm", type = int)
    args = p.parse_args()
    slots = args.slots
    pulses = args.pulses
    
    
    pauses = slots - pulses
    
    mod = pauses % pulses
    
    rythm = []
    
    
    if mod == 0:
        x = slots/pauses
        l = 0
        while l<slots:
    
            if l%x == 0:
                rythm.append(1)
            else:
                rythm.append(0)
    
            l = l + 1
    
        print (rythm)
    
    if mod != 0:
        i = 0
        j = 0
    
        while i < pulses:
            rythm.append([1])
            i = i + 1
    
        while j < pauses:
            rythm.append([0])
            j = j + 1
    
        last = len(rythm)
        last = last - 1
        last_len = len(rythm[last])
        x = slots%pauses
        y = pauses - x
    
        flag = True
    
        while flag == True:
            flag = False
    
            if (last_len != 1) or (rythm[last] != 0):
    
                flag = True
                i = 0
    
                while i < x:
                    rythm[i].append(rythm[last])
                    rythm.remove(rythm[last])
    
                    i = i + 1
    
                y = y - x
                x = x%y
                last = len(rythm)
                last = last - 1
                last_len = len(rythm[last])
    
        print (rythm)
    


Answer: `IndexError: list index out of range` \- means that the you are accessing a
value by position which doesnt exist.

for example:

    
    
    a = range(10) #length of a is 9, list indices start at 0
    print(a[10])  #accessing value by a index that doesn't exist, raises a IndexError exception
    

