Why does removing duplicates from a list produce [None, None] output?

前端 未结 3 648
长情又很酷
长情又很酷 2021-01-28 09:37

I am new to Python and I\'m not able to understand why I am getting the results with None values.

#Remove duplicate items from a list
def remove         


        
3条回答
  •  星月不相逢
    2021-01-28 09:45

    Although using a set is the proper way, the problem with your code, as the comments indicated, is that you are not actually returning unique_list from your function, you are returning the result of the list comprehension.

    def remove_duplicates(my_list):
        unique_list = []
        do = [unique_list.append(item) for item in my_list if item not in unique_list]
        return unique_list  # Actually return the list!
    
    print remove_duplicates([1,1,2,2]) -> result [1, 2]
    

    Here I simply made a throwaway variable do that is useless, it just "runs" the comprehension. Understand?

    That comprehension is storing a value each time you call unique_list.append(item) ... and that value is the result of the append method, which is None! So do equals [None, None].

    However, your unique_list is in fact being populated correctly, so we can return that and now your function works as expected.

    Of course, this is not a normal use for a list comprehension and really weird.

提交回复
热议问题