Skip to content Skip to sidebar Skip to footer

Algorithm: IndexError: List Index Out Of Range (Python)

I'm new to python and I wanted to know why my program is displaying 'IndexError: list index out of range' for line 4. Can anyone please help. # A is the array and N is the size of

Solution 1:

So the List index out of range comes from B = A[N] because N represents the total length of A. However, elements of a list are indexed from 0 up to N-1, which gives you the length (N-1) - 0 + 1 => N. If you want to assign B to the last element of A, you can do that by B = A[N-1], or B = A[-1], since negative indices point to elements of the list from the end. However, given you redeclare B = [0] * N, you could do away with the first assignment


Solution 2:

In Python, the first element of a list is addressed as zero rather than one. For example, to access the first element in a list called "numbers" you should write numbers[0] rather than numbers[1].

In B = A[N], you're trying to address the last element of list A by accessing A[N] (N corresponds to the length of list A). However, as previously explained, you have to minus one from this because the list starts at zero and not one. Therefore, the correct code would be B = A[N - 1].


Solution 3:

A =[1,78,46,4,34,10,50,2]
N = len(A)       # N = 8
def Algorithm(A,N):
    B = A[N]     # value of N is 8 and when you try to access A[8] its out of index range since the index is from 0 to 7
    B=[0]*N
    for i in range(1,N):
        B[A[i]]+=1
        i=1
    #for i <-- 1 to N
    for j in range(1,N):
    #for k <-- to B[j]
        for k in range(0,B[j]):
            A[i]=j
            i+=1
    return

Algorithm(A,N)
print(A)

I would like to point out other things that i have noted in your code.

A =[1,78,46,4,34,10,50,2]
N = len(A)       
def Algorithm(A,N):
    B = A[N]     
    B=[0]*N  # This line overwrites the above assignment. 
    for i in range(1,N):
        B[A[i]]+=1    # B[A[i]]  -- so i guess during execution the A[i] will be a value from list A . hence B[A[i]] might become B[78] , B[46] etc (sorry if i have misunderstood)
        i=1
    #for i <-- 1 to N
    for j in range(1,N):
    #for k <-- to B[j]
        for k in range(0,B[j]):
            A[i]=j
            i+=1
    return

Algorithm(A,N)
print(A)

Post a Comment for "Algorithm: IndexError: List Index Out Of Range (Python)"