Search code examples
pythonerror-handlingindexoutofrangeexception

Why does my list of zeroes result in IndexError?


I get an error on occurence[j] = 0. I do not really understand the origins of this error in my code, as it is of length dna, because I append at the top of the code len(dna) zeroes and then I assign some value to the same list occurence in my nested loop, where j can only reach the value of len(dna).

for i in range(len(dna)):
    occurence.append(0)

print(f"{len(dna)}")
print(f"{len(occurence)}")

#Calculating consecutive sequences and creating a 2D array occurence...
for i in types:
    for j in range(len(dna)):
        if (dna[j:j+len(i)] != i):
            occurence[j] = 0
        else:

            space = len(i)

            while(dna.find(i, space+len(i)) != -1):
                index = dna.find(i, space+len(i))
                space = space + len(i)
                if (index == len(i)):
                    occurence[j] += 1

    for k in range(len(occurence)):
        maximum = 0
        if(occurence[k] > maximum):
            maximum = occurence[k]
    counts.append(maximum)
    maximum = 0
    occurence.clear()

Solution

  • At the end of the first iteration over types, you call occurence.clear(), which will result in occurence being an empty list. Then, when you try to access occurence[j] on the second iteration, this throws an IndexError since the list is empty.

    I think you instead want to initialize your list inside the for i in types loop, e.g.:

    for i in types:
        occurence = [0] * len(dna)
        for j in range(len(dna)):
            ...
    

    You would then not need to call the clear method on your list, since it would be redefined as a list of zeroes on each iteration.