tags:

views:

156

answers:

5

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)

+5  A: 

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'])
Pär Wieslander
This works fine for me, plus it's simple, so I think I'll stick with this one for now, thanks everyone for your speedy and helpful input
chrism
@chrism: are you implying that anything else posted here is complex?
SilentGhost
no, but perhaps I'm too simple to figure out why my implementations of the other things I tried first didn't work?
chrism
+7  A: 

set(list1).difference(set(list2))

PiotrLegnica
A: 

You can do it with sets or a list comprehension:

unused = [i for i in list1 if i not in list2]
Max Shawabkeh
This works when I directly input sample lists in, but doesn't when I try to use my automatic lists (e.g. list1 = self.catList) - again with the iteration over non-sequence error, does this mean self.catList isn't really providing a list?
chrism
+1  A: 

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.

SilentGhost
A: 

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.

telliott99