Comparing list item values to other items in other list in Python
Question
I want to compare the values in one list to the values in a second list and return all those that are in the first list but not in the second i.e.
list1 = ['one','two','three','four','five']
list2 = ['one','two','four']
would return 'three' and 'five'.
I have only a little experience with python, so this may turn out to be a ridiculous and stupid way to attempt to solve it, but this what I have done so far:
def unusedCategories(self):
unused = []
for category in self.catList:
if category != used in self.usedList:
unused.append(category)
return unused
However this throws an error 'iteration over non-sequence', which I gather to mean that one or both 'lists' aren't actually lists (the raw output for both is in the same format as my first example)
Solution
Use sets to get the difference between the lists:
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1) - set(list2)
set(['five', 'three'])
OTHER TIPS
set(list1).difference(set(list2))
with set.difference
:
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1).difference(list2)
{'five', 'three'}
you can skip conversion of list2
to set.
You can do it with sets or a list comprehension:
unused = [i for i in list1 if i not in list2]
All the answers here are correct. I would use list comprehension if the lists are short; sets will be more efficient. In exploring why your code doesn't work, I don't get the error. (It doesn't work, but that's a different issue).
>>> list1 = ['a','b','c']
>>> list2 = ['a','b','d']
>>> [c for c in list1 if not c in list2]
['c']
>>> set(list1).difference(set(list2))
set(['c'])
>>> L = list()
>>> for c in list1:
... if c != L in list2:
... L.append(c)
...
>>> L
[]
The problem is that the if
statement makes no sense.
Hope this helps.