-1
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?

4 Answers4

3

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)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • You could also use a set to keep track of what has been seen, since set lookup is `O(1)`: `seen = set() new_l = [] for i in l: if i not in seen: new_l.append(i) seen.add(i)` – RoadRunner Jan 13 '18 at 03:34
  • @RoadRunner great idea, please see my recent edit. – Ajax1234 Jan 13 '18 at 03:51
2

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

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • 1
    You can also just do `sorted(set(my_list))` here. No need to wrap `list()` if you apply `sorted()` to a set. – RoadRunner Jan 13 '18 at 03:22
1
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))
1

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))
jknight
  • 91
  • 6