python – Why tag me list index out of range?

Question:

Can someone tell me what error I have in my code if it's not too much trouble.

def CreaLista(k):
    L = []
    for i in range(k+1):
        L.append(0)
    return L

def CountingSort(A,k):
    C=CreaLista(k)
    B=CreaLista(len(A)-1)
    for j in range(1, len(A)):
        C[A[j]] = C[A[j]]+1
    for i in range(1, k+1):
        C[i]=C[i]+C[i-1]
    for j in range(len(A)-1,0,-1):
        B[C[A[j]]]=A[j]
        C[A[j]]=C[A[j]]-1
    return B

lista = [0,9,7,81,4,5,68,3,541]
k = len(lista[1:])
CountingSort(lista, k)

This is the error it gives me:

IndexError                                Traceback (most recent call last)
<ipython-input-1-d6ba25f80b3f> in <module>()
     19 lista = [0,9,7,81,4,5,68,3,541]
     20 k = len(lista[1:])
---> 21 CountingSort(lista, k)

<ipython-input-1-d6ba25f80b3f> in CountingSort(A, k)
      9     B=CreaLista(len(A)-1)
     10     for j in range(1, len(A)):
---> 11         C[A[j]] = C[A[j]]+1
     12     for i in range(1, k+1):
     13         C[i]=C[i]+C[i-1]

IndexError: list index out of range

Answer:

In Python, lists start at 0. In your case, in the first iteration of the first for, A[j] is equal to 9. C only has 9 elements, so you could only access up to C[8] . In any case, I recommend that you use the enumerate function instead of using range. For loops would be much cleaner:

for key, value in enumerate(A):
    pass
Scroll to Top