14. remove duplicates. why didn't my first code work


#1

The first function I didn't make myself but the other one I made.

  def remove_duplicates(nums):
        newList = []
        for i in nums:
            if i not in newList: 
                newList.append(i)
        
        return newList    

    print remove_duplicates([4, 5, 5, 4])

    def remove_uplicates(Nums):
        NewList = []
        for j in Nums:
            if j == j:
                Nums.remove(j)
                NewList.append(j)
        
        return NewList    

    print remove_uplicates([4, 5, 5, 4])

So my question is why does codecademy accept the first function and not the one i made which is the last function? I changed the letters in them so i could check if I got the same outcome and I did. I was so glad when i did the function with out coming here but then it said maybe you should make copy. so i went here and got the function which is listed first.


#2

Changing the list will have effects on how the loop progresses. You have to account for this, or avoid changing what you're iterating through.

I also think that j is always going to be equal to j


#3

Yeah, in that case i could just take away the if statment! LOL
So what i've done is to take two things from the list! so i have altered the list that was given? So what the first function does is to take the list make it so that we copy and take away the numbers that is duplicated then we print the list we made? did i get that right?


#4

Yeah sorry, can't follow along in that description. Either know exactly what you are saying, or get less technical, so that you know exactly what you're saying.

Here's what was happening for your faulty version:

my_list = range(100)
my_iterator = iter(my_list) # This walks through the list, same as a for-loop

print next(my_iterator) # 0
print next(my_iterator) # 1
print next(my_iterator) # 2

# Let's remove the first element and see what
# comes out of the iterator after that
del my_list[0]
print next(my_iterator) # 4

# Oh dear, we skipped 3 because we caused things to move in the list,
# the iterator was affected

#5

thank you! got it now