It works but site gives me an error


#1
def remove_duplicates(nums):
    nums.sort()
    index = 0
    for num in nums:
        while index + 1 < len(nums):
            if nums[index] == nums[index + 1]:
                del nums[index]
            else:
                break
        index += 1
    return nums

Here is my code and it works but site gives me an error saying that I shouldn't modify nums instead I should make a copy first but I dont understand how that could be relevant in any case and furthermore even If I make a new variable to hold the value of nums it doesnt accept it


#2

Hello, @odrekci!
That warning was to simply remind that some moments when we iterate through a function and remove some elements from it, at the same time, it might cause some errors due to that.
In your case, such thing doesn't seem to have, the code is even working correctly and bringing back the expected result, but there are moments that doing such things will cause an error.

Last time I saw something like this was with a user who got a list from range(len(listName)). He was iterating over this list, generated by range, and removing specific elements. In that case, the error occured because you were making your list shorter, at least that's what I think.

Even if your code is correct, follow the instructions. Regardless if you want to follow or not, that's your only was to pass the lesson.

Have you tried doing the following ?

newList = oldList[:]

This will copy the values from the old list to the new list, other than passing the reference of a list to another.
Remember: whenever we use functions and we pass, as argument, a list we are passing the reference of it, which means that any modification that we do inside of our function with the list, will cause the original list to be also modified.

Hope this helps you understand why all of this!
If I wasn't clear or my answer wasn't enough, let me know and I'll find another way to explain.


#3

I think the thing would be to make a new list just with the non repeated ones:

def remove_duplicates(nums):
purifiedlist = []
for number in nums:
if number in purifiedlist:
pass
else:
purifiedlist.append(num)
return purifiedlist

It worked fine for me.


#4

Thank you g4be! As always you reply with a solution and a clear explanation.


#5

No problem, Odrekci! Glad to help!