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
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.