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

3
  • Does it need to stay a list? Making it a set gets rid of all duplicates, and even as a set, you can make it a list again, Commented Jan 13, 2018 at 3:08
  • Hello Davy M, if I make it a set will it get rid of the duplicate elements? Commented Jan 13, 2018 at 3:14
  • list(set(List)) will return unique list Commented May 21, 2018 at 12:00

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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 great idea, please see my recent edit.
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))

1 Comment

You can also just do sorted(set(my_list)) here. No need to wrap list() if you apply sorted() to a set.
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))

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.