Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This works BUT WHY?

Tags:

python

I'm learing Python on codecademy and came across this solution for a function that's meant to remove duplicates from a list of numbers:

x = [1, 1, 2, 2]

def remove_duplicates(x):
    p = []
    for i in x:
       if i != i:
           p.append(i)
    return i

I ran this in pycharm with some print statements and just got an empty list. I'm only curious because when I do this in my head, it makes no sense, but codecademy accepts this as an answer. Is it just a fluke? Or is this on a level I don't understand yet?

like image 815
Thomas Cho Avatar asked Mar 11 '23 09:03

Thomas Cho


2 Answers

You are correct: it doesn't make any sense. First, it creates a list called p that gets each item that is not equal to itself. The only object that I know of that is not equal to itself is NaN, but you don't have any of those, so p is just an empty list. Defining p is useless, however, because it isn't even returned. What is returned is i, which is assigned to each item in the last, so it is the last item in the list by the end of the function. In short, that function is equivalent to this:

def remove_duplicates(x):
    return x[-1]

I haven't heard what the function is supposed to return, but perhaps it is supposed to return the number of non-duplicate items. If it is, it "works" just because the last item in the list happens to be the number of non-duplicate items.

like image 101
zondo Avatar answered Mar 19 '23 06:03

zondo


Take a look to this snippet to see the pythonic way to remove duplicated (good_result) and also to understand why your code doesn't make any sense:

x = [1, 1, 2, 2]


def remove_duplicates(x):
    p = []
    for i in x:
        if i != i:
            p.append(i)
    return i

good_result = list(set(x))
print good_result
print remove_duplicates(x)

As you can see, your function is not returning the filtered list without duplicate values, it's just returning the last element of the list (index=-1). So codeacademy shouldn't accept that snippet as a valid answer to the question how to remove duplicateds from a list for sure.

Now, if we assume what codeacademy was really asking is for the number of unique values from a list, then is a casuality your broken code gives the right answer, which is the same as len(good_result). It worked just by luck just to say, it doesn't mean your code is correct :)

like image 38
BPL Avatar answered Mar 19 '23 07:03

BPL