Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing elements in two lists when keeping duplicates is desired in Python

Tags:

python

list

I'd like to compare two lists. I'd like to find elements in the first list that don't have a corresponding entry in the second list (order doesn't matter):

a = ['hi', 'hi', 'bye', 'hi']
b = ['hi', 'hi', 'bye']

So I would like the output to be

c = ['hi']  

since the first list has an extra 'hi' in it that doesn't appear in the second list.

If I do one of the usual techniques, I can use a list comprehension:

[x for x in a if x not in b]

which gives me [], which is not what I want.

Things I've tried involve using the set operator, which have the same outcome, since that operation reduces the members of the list to uniqueness.

This seems like a simple operation. Do I need to enumerate each element in the lists first, and create tuples to compare? Do I need to put them into a Counter dict? All this sounds a little bit like overkill when I just want to a simple comparison of the elements in a list!

like image 591
Monica Heddneck Avatar asked Apr 17 '26 12:04

Monica Heddneck


1 Answers

Counter objects support multi-set operations:

>>> from collections import Counter
>>> a = ['hi', 'hi', 'bye', 'hi']
>>> b = ['hi', 'hi', 'bye']
>>> Counter(a) - Counter(b)
Counter({'hi': 1})

Rebuilding a list from the Counter:

>>> list(counter.elements())
['hi']
like image 116
wim Avatar answered Apr 19 '26 02:04

wim



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!