Remove_duplicates: How to solve this error?


#1

def remove_duplicates(num):
    new = []
    for i in num:
        del num[i]
        for a in num:
            if i is a:
                new.append(i)
    return new
    
print remove_duplicates([1,1,2,2,5,5])

Traceback (most recent call last):
File "python", line 10, in
File "python", line 4, in remove_duplicates
IndexError: list assignment index out of range


#2

please walk us through your thought process of how you go about solving this problems

here are some of my thoughts:

Using del doesn't seem like a good idea at all

here:

if i is a:

why would you use is keyword? We can use in keyword to check if something ( a value) is present in list or string, and which keyword did we learn to reverse a condition?


#3

I didn't use in because a is not a list, but a value in num.
I used del num[i] to remove the value within when counting the number in num, so that in the second for loop the number will be excluded.

However, i appeared that when i put in print remove_duplicates([1,1,2,2]) there is no error. why?


#4

is keyword tests for identity, not equality. Sure you not simply want to use == which checks if is equal? I still can't entirely see where your solution is going

because all this values within list are in index range, here:

    for i in num:
        del num[i]

i contains values from the list, not indexes, while del removes based on index

so if you have:

print remove_duplicates([5])

it will thrown an error here:

del num[5]

given there is no index 5 in this list


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.