How to remove every occurrence of sub-list from list

  • A+

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 should be [2, 3, 4]

For strings you could use this:

'2123124'.replace('12', '') 

But AFAIK this does not work for lists.

This is not a duplicate of Removing a sublist from a list since I want to remove all sub-lists from the big-list. In the other question the result should be [5,6,7,1,2,3,4].

Update: For simplicity I took integers in this example. But list items could be arbitrary objects.


if big_list = [1, 2, 1, 2, 1] and sub_list = [1, 2, 1], I want the result to be [2, 1].


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] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: