Remove_duplicates - returns empty list


#1



Hi

Please can you assist me with my code below. I think it really is a very small error I am making - I am not sure if perhaps I have made a mistake when creating a copy of my original list or not?

Thank you in advance.


Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [] instead of [4, 5]


def remove_duplicates(x):
    x = []
    new_list = list(x)
    for data in x:
        if data not in new_list:
            new_list.append(data)
    return new_list


#2

here:

def remove_duplicates(x):
    x = []

you are overwriting your function parameter. So the list will be empty even before the loop starts


#3

Thank you stetim94

Even when I remove the "x = []" it gives the same error?


#4

but then new_list is not empty, make new_list an empty list


#5

I see... thank you - it works.

But I would like to ask something about the x = [] part. The question said that the element within the function needs to be a list. So if I do not explicitly state x = [] then how does python know that the element will be a list?


#6

because you pass a list as argument on function call which will then be passed into the function parameter (x)


#7

Ah, so when you say:

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

only then does python know that the element is a list. Thank you... really appreciate it!


#8

yes, function only execute when called, so until called the function parameter is simply a placeholder


#9

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