Shahbaz
Shahbaz

Reputation: 825

How to remove all repeating elements from a list in python?

I have a list like this:-

[1,2,3,4,3,5,3,6,7,8]

I want to remove the repeating element (here:- 3) completely from the list like this:-

[1,2,4,5,6,7,8]

How do I implement this in python such that not only the first occurrence of duplicate element is removed but all the duplicating values are removed

Upvotes: 5

Views: 2160

Answers (4)

Dock
Dock

Reputation: 464

Use a set. To get rid of all repeating values use this:

a = [1,2,3,4,3,5,3,6,7,8]
print(a)
a = list(set(a))
print(a)

That will output

[1,2,3,4,3,5,3,6,7,8]
[1,2,4,5,6,7,8]

Upvotes: 0

Abhinandan Das
Abhinandan Das

Reputation: 1

A good and efficient way will be to use pandas

import pandas as pd
sample_list = [1,2,3,4,3,5,3,6,7,8]
unique_list = list(pd.Series(sample_list).drop_duplicates())

>> unique_list    
>> [1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 0

roshaga
roshaga

Reputation: 257

This code should work

#Finding duplicate
def dup(x):
    s = len(x)
    duplicate = []
    for i in range(s):
        k = i + 1
        for j in range(k, s):
            if x[i] == x[j] and x[i] not in duplicate:
                duplicate.append(x[i])
    return duplicate

#begining
list1 = [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
#Finding duplicate
dup_list = (dup(list1))
#removing duplicates from the list
final_list = list(set(list1) - set(dup_list))
print(final_list)

Upvotes: 1

fuenfundachtzig
fuenfundachtzig

Reputation: 8352

You can use Counter from collections to count the number of occurrences and select those elements which appear exactly once using a list comprehension:

from collections import Counter
a = [1,2,3,4,3,5,3,6,7,8]
[k for k, v in Counter(a).items() if v == 1]

(Counter basically returns a dictionary where elements are stored as keys and their counts are stored as values.)

Upvotes: 7

Related Questions