Hi I am looking for a way to remove a sublist from a list. something like this:
a=range(1,10)
a.remove([2,3,7])
print a
a=[1,4,5,6,8,9]
Hi I am looking for a way to remove a sublist from a list. something like this:
a=range(1,10)
a.remove([2,3,7])
print a
a=[1,4,5,6,8,9]
>>> a=range(1,10)
>>> [x for x in a if x not in [2,3,7]]
[1, 4, 5, 6, 8, 9]
a=range(1,10)
b = filter(lambda x:x not in set([2,3,7]), a)
print b
b = [1, 4, 5, 6, 8, 9]
update:
a=range(1,10)
itemsToRemove = set([2,3,7])
b = filter(lambda x: x not in itemsToRemove, a)
or
b = [x for x in a if x not in itemsToRemove]
Others have suggested ways to make newlist after filtering e.g.
newl = [x for x in l if x not in [2,3,7]]
or
newl = filter(lambda x: x not in [2,3,7], l)
but from your question it looks you want in-place modification for that you can do this, this will also be much much faster if original list is long and items to be removed less
l = range(1,10)
for o in set([2,3,7,11]):
try:
l.remove(o)
except ValueError:
pass
print l
output: [1, 4, 5, 6, 8, 9]
I am checking for ValueError exception so it works even if items are not in orginal list.
Also if you do not need in-place modification solution by S.Mark
is simpler.
The simplest way is
>>> a=range(1,10)
>>> for x in [2,3,7]:
... a.remove(x)
...
>>> a
[1, 4, 5, 6, 8, 9]
One possible problem here is that each time you call remove(), all the items are shuffled down the list to fill the hole. So if a
grows very large this will end up being quite slow.
This way builds a brand new list. The advantage is that we avoid all the shuffling of the first approach
>>> removeset = set([2,3,7])
>>> a=[x for x in a if x not in removeset]
If you want to modify a
in place, just one small change is required
>>> removeset = set([2,3,7])
>>> a[:]=[x for x in a if x not in removeset]
>>> a=range(1,10)
>>> for i in [2,3,7]: a.remove(i)
...
>>> a
[1, 4, 5, 6, 8, 9]
>>> a=range(1,10)
>>> b=map(a.remove,[2,3,7])
>>> a
[1, 4, 5, 6, 8, 9]