Home > Back-end >  How to get a list with only unique numbers? (Python)
How to get a list with only unique numbers? (Python)

Time:09-23

I want to write a program that checks for duplicate values and removes them. So for example I want from this:

list = [2,6,8,2,9,8,8,5,2,2]

To get only this:

uniques = [6,9,5]

I can't seem to find a good way to compare every item with each other to see if they are equal and them remove them. Any help will be very appreciated!

CodePudding user response:

Use collections.Counter:

>>> from collections import Counter                                         
>>> lst = [2,6,8,2,9,8,8,5,2,2]                                             
>>> c = Counter(lst)                                                        
>>> [x for x in c if c[x] == 1]                                             
[6, 9, 5]

Other than using count or in for each element, this should be O(n) instead of O(n²).

CodePudding user response:

If you want to preserve the order of the elements too, follow this best method :

uniques = list(dict.fromkeys(list))

print(uniques)

CodePudding user response:

Given that you want a list of values that appear only once in your list, this should work. I used a hashmap to store the count of values in the the list and then added the keys which have a count of 1 into unqiue.

l = [2,6,8,2,9,8,8,5,2,2]
unique = []
count = {}

for i in l:
    if count.get(i) is None:
        count[i] = 1
    else:
        count[i] =1

for i in count.keys():
    if count[i] == 1:
        unique.append(i)

print(unique)

Output

[6, 9, 5]

CodePudding user response:

list = [2,6,8,2,9,8,8,5,2,2]
uniques = []
for i in range(len(list)):
    if list.count(list[i])==1:
        uniques.append(list[i])

CodePudding user response:

list = [2,6,8,2,9,8,8,5,2,2]
uniques = []
for i in list:
    if i not in uniques:
        uniques.append(i)

CodePudding user response:

Try this:

lst = [2,6,8,2,9,8,8,5,2,2]
[l for l in set(lst) if lst.count(l) == 1]
# [5, 6, 9]
  • Related