How to remove every occurrence of sub-list from list
You'd have to implement it yourself. Here is the basic idea:
def remove_sublist(lst, sub): i = 0 out = [] while i < len(lst): if lst[i:i+len(sub)] == sub: i += len(sub) else: out.append(lst[i]) i += 1 return out
This steps along every element of the original list and adds it to an output list if it isn't a member of the subset. This version is not very efficient, but it works like the string example you provided, in the sense that it creates a new list not containing your subset. It also works for arbitrary element types as long as they support ==
. Removing [1,1,1]
from [1,1,1,1]
will correctly result in [1]
, as for a string.
Here is an IDEOne link showing off the result of
>>> remove_sublist([1, 'a', int, 3, float, 'a', int, 5], ['a', int])[1, 3, <class 'float'>, 5]
Try del
and slicing
. The worst time complexity is O(N^2)
.
sub_list=['a', int]big_list=[1, 'a', int, 3, float, 'a', int, 5]i=0while i < len(big_list): if big_list[i:i+len(sub_list)]==sub_list: del big_list[i:i+len(sub_list)] else: i+=1print(big_list)
result:
[1, 3, <class 'float'>, 5]
A recursive approach:
def remove(lst, sub): if not lst: return [] if lst[:len(sub)] == sub: return remove(lst[len(sub):], sub) return lst[:1] + remove(lst[1:], sub)print(remove(big_list, sub_list))
This outputs:
[2, 3, 4]