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