I have two lists:
big_list = [2, 1, 2, 3, 1, 2, 4]
sub_list = [1, 2]
I want to remove all sub_list occurrences in big_list.
result
How about this:
def remove_sublist(lst, sub):
max_ind_sub = len(sub) - 1
out = []
i = 0
tmp = []
for x in lst:
if x == sub[i]:
tmp.append(x)
if i < max_ind_sub: # partial match
i += 1
else: # found complete match
i = 0
tmp = []
else:
if tmp: # failed partial match
i = 0
out += tmp
if x == sub[0]: # partial match
i += 1
tmp = [x]
else:
out.append(x)
return out
Performance:
lst = [2, 1, 2, 3, 1, 2, 4]
sub = [1, 2]
%timeit remove_sublist(lst, sub) # solution of Mad Physicist
%timeit remove_sublist_new(lst, sub)
>>> 2.63 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> 1.77 µs ± 13.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Update
My first solution had a bug. Was able to fix it (updated my code above) but the method looks way more complicated now. In terms of performance it still does better than the solution from Mad Physicist on my local machine.