Home > Back-end >  IndexErrorL list index out of range, when removing items from list
IndexErrorL list index out of range, when removing items from list

Time:12-04

I'm trying to make code that removes duplicates from a sorted list. Here is the code I have made:

def rduplicate(L):
    Lc = L.copy()
    for i in range(len(L)):
        if L[i]==L[i 1]:
            Lc.remove(L[i])
    return Lc

L=[1,2,3,3,5,6]
print(rduplicate(L))

I can't see why the error, "IndexError: list index out of range" is produced.

CodePudding user response:

Don't remove it from a copy. Just create a new list instead:

L=[1,2,3,3,5,6]
unique_L = [i for i,j in zip(L,L[1:]) if i!=j]   [L[-1]]
#[1, 2, 3, 5, 6]

CodePudding user response:

Like mentioned in the comment, L[i 1] tries to access an element that's not in the list in the last iteration of the loop.

You can fix this by skipping that last iteration. This works:

def rduplicate(L):
    Lc = L.copy()
    for i in range(len(L)-1):
        if L[i]==L[i 1]:
            Lc.remove(L[i])
    return Lc

CodePudding user response:

You have to add

if L[i] == len(L):
        break

Before your if statement like this code which works:

def rduplicate(L):
    Lc = L.copy()
    for i in range(len(L)):
      if L[i] == len(L):
        break
        if L[i]==L[i 1]:
            Lc.remove(L[i])  
    return Lc

L=[1,2,3,3,5,6]
print(rduplicate(L))

The error comes after running the loop 6 times and looking for the next (7th) element that doesn't exist.

  • Related