python: removing multiple item in list
Question:
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]
Answers:
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 ... ]
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)
a=[1,2,3,4,5]
b=[1,2,3,5,5,5,7,8,9,0]
c = set(a+b)
print(c)
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]
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 ... ]
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)
a=[1,2,3,4,5]
b=[1,2,3,5,5,5,7,8,9,0]
c = set(a+b)
print(c)