Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove NOT duplicates value from list

The scenario is this something like this:

After joining several lists using:

list1 = ["A","B"]
list2 = ["A","B","C"]
list3 = ["C","D","E"]

mainlist = list1 + list2 + list3
mainlist.sort()

mainlist now looks like that:

mainlist = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'E']

I would like to remove anything that is not a duplicate value. If the value in question is already present in the list it must not be touched and while if it is present only once in the mainlist I would like to delete it.

I tried to use this approach but seems something isn't working:

for i in mainlist:
    if mainlist.count(i) <= 1:
        mainlist.remove(i)
    else:
        continue

but what I return is a list that looks like the following:

mainlist = ['A', 'A', 'B', 'B', 'C', 'C', 'E'] #value "D" is not anymore present. Why?

What i would like to return is a list like that:

mainlist = ['A', 'A', 'B', 'B', 'C', 'C'] #All values NOT duplicates have been deleted

I can delete the duplicates with the below code:

for i in mainlist:
    if mainlist.count(i) > 1:
        mainlist.remove(i)
    else:
        continue

and then as a final result:

mainlist = ['A','B','C']

But the real question is: how can I delete the non-duplicates in a list?

like image 370
Turi Avatar asked Jun 08 '26 14:06

Turi


1 Answers

You can find duplicates like this:

duplicates = [item for item in mainlist if mainlist.count(item) > 1]
like image 151
Luis Fernando Ushiña Avatar answered Jun 11 '26 03:06

Luis Fernando Ushiña



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!