tags:

views:

153

answers:

4

How can I fix this statement:

for i in LISTA and i not in LISTB:
   print i
+8  A: 
for i in LISTA:
  if i not in LISTB:
    print i
ghostdog74
+6  A: 
new_list = set(LISTA) -  set(LISTB) # if you don't have duplicate
for i in new_list:
   print i

Or :

for i in LISTA:
   if i in LISTB:
      continue
   print i
singularity
I can only upvote in a few minutes, but this list subtraction solves my problem. Thank you.
relima
Sets are awesome if you don't need your duplicates to remain. Also might be important to point out that `new_list` is a set not a list.
offsound
Sets also lose ordering. The efficient thing to do in general is to only create a set for `listb`, where ordering and duplicates never matter, so `i in listb` is efficient.
Glenn Maynard
+5  A: 

A more sophisticated solution. This is a simple intersection complement.

a = set([1, 2, 3])
b = set([3, 4, 5])

print(a - b)
Mike
+1 A very clean solution.
Xorlev
+2  A: 
for i in (i for i in LISTA if i not in LISTB):
    print i

The part in parentheses is a generator expression. The benefit of this over other methods that is that it doesn't create duplicate (temporary) sets or list objects. This is especially important if LISTA and/or LISTB are really large.

ma3