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]
2
  • Reason: Loop “Forgets” to Remove Some Items Commented Sep 7, 2014 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 Commented Sep 7, 2014 at 20:53

2 Answers 2

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 ... ]
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this doesn't actually remove them from b, it creates a new list containing those items not in a.
@kender, yes, python is :)
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)

1 Comment

don't use a list comprehension when what you need is a loop... Also, this won't remove all occurences of duplicate items.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.