In a list, I have duplicate elements that I want to remove.
The following code doesn't work:
Note: temp containts the list of indexes of elements that I want to remove.
x is my list.
temp = self.list_duplicates(x)
for index in tmp:
del x[index]
In a list, I have duplicate elements that I want to remove.
The following code doesn't work:
Note: temp containts the list of indexes of elements that I want to remove.
x is my list.
temp = self.list_duplicates(x)
for index in tmp:
del x[index]
Build a new list with a comprehension:
x = [element for (i,element) in enumerate(x) if i not in temp]
If you want to remove only duplicates, i.e. leaving one copy of the original, there is a better way to do that:
from collections import OrderedDict
x = list(OrderedDict.fromkeys(x))
x.pop(index) will remove the item at index. However, x = [x[i] for i in range(len(x)) if x[i] not in x[:i]] will remove the duplicates more quickly.
You can filter the list with the following:
Edit: Works now for list of indices
x = list(filter(lambda item: x.index(item) not in temp, x))
No one addressed the first part of the question. So, for removing duplicate items its wise to use set(), it removes the duplicate items and returns a arbitrary list of unique items.
lst = [1,1,2,3,4,4]
new_lst = list(set(lst))
print(lst)
It will return unique list of elements in an arbitrary manner Eg : [1,4,2,3]