Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 751
Shahbaz Avatar asked Dec 11 '20 16:12

Shahbaz


3 Answers

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

like image 175
fuenfundachtzig Avatar answered Oct 04 '22 21:10

fuenfundachtzig


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)
like image 41
roshaga Avatar answered Oct 04 '22 21:10

roshaga


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]

And there's a lot on Google, so you could've just looked it up (which is why you have a downvote)

like image 42
Dock Avatar answered Oct 04 '22 21:10

Dock