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

前端 未结 3 651
长情又很酷
长情又很酷 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 10:06

    The problem with your code is that the method list.append returns None. You can test this easily with the following code:

    myList=[1, 2, 3]
    print myList.append(4)
    

    So, a solution for you would issue would be

    def remove_duplicates(myList):
        alreadyIncluded = []
        return [item for item in myList if item not in alreadyIncluded and not alreadyIncluded.append(item)]
    print remove_duplicates([1,1,2,2]) 
    

    The idea is that you will begin with an empty list of aldeady included elements and you will loop over all the elements in list, including them in the alreadyIncluded list. The not is necessary because the append will return None and not None is True, so the if will not be affected by the inclusion.

    You were including a list of the result of the appends (always None), but what you need is a list of the elements that passed the if test.

    I hope it helps.

提交回复
热议问题