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

Viewed 2176

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!

2 Answers
Related