I have two lists in Python, like these:
temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']
I need to create a third
Here's a Counter
answer for the simplest case.
This is shorter than the one above that does two-way diffs because it only does exactly what the question asks: generate a list of what's in the first list but not the second.
from collections import Counter
lst1 = ['One', 'Two', 'Three', 'Four']
lst2 = ['One', 'Two']
c1 = Counter(lst1)
c2 = Counter(lst2)
diff = list((c1 - c2).elements())
Alternatively, depending on your readability preferences, it makes for a decent one-liner:
diff = list((Counter(lst1) - Counter(lst2)).elements())
Output:
['Three', 'Four']
Note that you can remove the list(...)
call if you are just iterating over it.
Because this solution uses counters, it handles quantities properly vs the many set-based answers. For example on this input:
lst1 = ['One', 'Two', 'Two', 'Two', 'Three', 'Three', 'Four']
lst2 = ['One', 'Two']
The output is:
['Two', 'Two', 'Three', 'Three', 'Four']