0
votes

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 the array.
A =[1,78,46,4,34,10,50,2]
N = len(A)
def Algorithm(A,N):
    #B <- Array[N]
    B = A[N]
    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)

Error:

  2 N = len(A)
  3 def Algorithm(A,N):
  4     B = A[N]
  5     B=[0]*N
  6     for i in range(1,N):

IndexError: list index out of range

3
list indices go from 0 up to and including array length minus 1.Michael Butscher
A has eight elements. A[8] does not exist, because Python lists are zero-indexed. Valid indexes for A are 0 thru 7.John Gordon

3 Answers

1
votes

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

0
votes

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].

0
votes
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)