What am I doing wrong?


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/removeduplicates?action=lesson_resume

This is the error message I received:
remove_duplicates([4, 5, 5, 4]) returned [4] instead of [4, 5]

The assignment is to remove duplicates from a list, which I named x.
I am brand new to this, so I am sure to be doing some very silly or odd mistakes… I apologize in advance
I am not sure if it is possible to use the range function for this.
Also, if it necessary to increase n every time one goes through the loop in a for loop with a specified range? I mean, wouldn’t the loop stop after n has exceeded the range?
Thank you!


def remove_duplicates(x):
    new_list=[]
    for n in range(0,len(x)-1):
        if x[n] not in new_list:
            new_list.append(x[n])
            n=+1
            return new_list



#2

range is certainly possible, although why would you od len(x) -1? range does not include its stop value so there is no reason to subtract one

n=+1 is also not needed, range will increase n, even if you would, the shorthand is +=

a function ends the moment a return keyword is reached

so your function ends in the first iteration of the loop, but to get the correct list the loop need to make all iterations

so return should be placed outside the loop


#3

Thank you so much!
I did not remember that about the range function, or about return! It works perfectly now
’’‘
def remove_duplicates(x):
new_list=[]
for n in range(0,len(x)):
if x[n] not in new_list:
new_list.append(x[n])
return new_list
’’’


#4

yes, you could also loop over x directly:

for n in x:

now n will contain the values from the list directly, saves some code

range() is useful when you want to update elements in your list (given it gives indexes), given you do not update elements here, its not needed


#5

Thank you for the tip!


#6