List=[1,1,1,1,2,2,2,2,3,3,3,3]
From the above list, I want to delete the 1st, 2nd, 3rd and the 5th, 6th, 7th and so on until I get a list [1,2,3]. If the list doesn't stop at 3 but continue, how should I delete all the other elements?
To remove duplicates and retain the order, you could use itertools.groupby:
import itertools
l =[1,1,1,1,2,2,2,2,3,3,3,3]
new_l = [a for a, _ in itertools.groupby(l)]
Output:
[1, 2, 3]
However, if you are looking for a way to remove all duplicates, rather than long runs of the same value, use an empty set and for-loop:
new_l = {}
for i in l:
if i not in new_l:
new_l.add(i)
O(1): seen = set() new_l = [] for i in l: if i not in seen: new_l.append(i) seen.add(i)If your list is ordered, you can do like this:
my_list = [1,1,1,1,2,2,2,2,3,3,3,3]
sorted(set(my_list))
if the order does not matter:
list(set(my_list))
Thanks @ RoadRunner in the comments for the assist from sorted(list(set(my_list))) to sorted(set(my_list))
sorted(set(my_list)) here. No need to wrap list() if you apply sorted() to a set.
list(set(List))will return unique list