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?
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)
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))
def removeDuplicates(arr, n):
if n == 0 or n == 1:
return n
temp = list(range(n))
j = 0;
for i in range(0, n-1):
if arr[i] != arr[i+1]:
temp[j] = arr[i]
j += 1
temp[j] = arr[n-1]
j += 1
for i in range(0, j):
arr[i] = temp[i]
return j
To call:
lst = [1,1,2]
removeDuplicates(lst, len(lst))
You want to convert the list into a set, which will remove the duplicates for you. Converting the set back to a list might make it easier for you to manipulate.
List = [1,1,1,1,2,2,2,2,3,3,3,3]
List = list(set(List))