14 remove_duplicates "list assignment index out of range"


def remove_duplicates(a):

for nums in a:
for b in range(len(newlist)):
for c in range(1,len(newlist)):
if a[b] == a[c]:
del newlist[c]
return newlist

so my code is ment to look for numbers other than the one being com paired to by cycling through two lists. b is the first index number for example on the test [4,5,5,4] I want it to run like this.
b in range (len(a)) goes to b = [0,1,2,3]
for b = 0. c=range(1,len(a)) which should go to c=[1,2,3]
giving b=0 and c=1
if a[b] == a[c]
if a[0] == a[1]
4=5 ,false. It then goes back to the for loop.
4=5 ,false once again repeat the loop.
4==4 ,true executes the then statement.
del newlist[c] which was filled earlier with the numbers from the list so that we arn't changing the initial list. [4,5,5,4]
del newlist[3], new list should now contain [4,5,5] and after completing the for loop go back to the b for loop and go to b=[2] then find the corresponding 5 and delete that one.

but instead i get error:"list assignment index out of range"
where did i go wrong?



The problem that results from deleting elements while iterating is that the range() is still unchanged so will exceed the true last element of the iterated list.

l1 = [1,2,3,4,5]
r1 = range(len(l1))
print l1[len(r1)-1]
del l1[0]
print l1[len(r1)-1]

# 5

    print (l1[len(r1)-1])
IndexError: list index out of range


so how would i fix that?


One approach may be to use a while loop that monitors the object length and end of data. Give this some thought and show us what you come up with. The proviso when deleting is that the original list is not preserved.

If you wish to stick with a range, then the simplest approach is to use a new empty list and append each new element only if the element does not already exist in the new list. Deletion from the old list is unnecessary in this case.

    temp = []
    for element in original:
        if element not in temp:
    return temp