0

I want to remove every item in b that's in a, the out would be [7,8,9,0], how can I do it, this doesn't seem to work

In [21]:
a=[1,2,3,4,5]
b=[1,2,3,5,5,5,7,8,9,0]
for i in b:
    if i in a:
        print i
        b.remove(i)
print b
#
Out[21]:
1
3
5
[2, 5, 5, 7, 8, 9, 0]
shx2
  • 61,779
  • 13
  • 130
  • 153
Hon
  • 11
  • 1
  • 3
  • Reason: [Loop “Forgets” to Remove Some Items](http://stackoverflow.com/questions/17299581/loop-forgets-to-remove-some-items) – Ashwini Chaudhary Sep 07 '14 at 20:37
  • 1
    Swapping the order of iteration to list 'a' and then list 'b and also replacing your inner "if" with "while" will also work, but I like the solution by @shx2 – amehta Sep 07 '14 at 20:53

2 Answers2

5

Use list comprehension and the in operator.

b = [ elem for elem in b if elem not in a ]

For speed, you can first change a into a set, to make lookup faster:

a = set(a)

EDIT: as pointed out by @Ignacio, this does not modify the original list inplace, but creates a new list and assigns it to b. If you must change the original list, you can assign to b[:] (read: replace all elements in b with the elements in RHS), instead of b, like:

b[:] = [ elem for ... ]
shx2
  • 61,779
  • 13
  • 130
  • 153
0

This will remove the items from list 'b' that are already in list 'a'

[b.remove(item) for item in a if item in b]

Updated as per @shx2:

 for item in a:
     while item in b:
         b.remove(item)

Also, you could make it faster by making list 'a' a set

 for item in set(a):
     while item in b:
         b.remove(item)
amehta
  • 1,307
  • 3
  • 18
  • 22
  • 2
    don't use a list comprehension when what you need is a loop... Also, this won't remove all occurences of duplicate items. – shx2 Sep 07 '14 at 20:44