Monday, 30 July 2018

How to remove every occurrence of sub-list from list

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.

Update2:

if big_list = [1, 2, 1, 2, 1] and sub_list = [1, 2, 1], I want the result to be [2, 1] (like '12121'.replace('121', ''))

Update3:

I don't like copy+pasting source code from StackOverflow into my code. That's why I created second question at software-recommendations: https://softwarerecs.stackexchange.com/questions/51273/library-to-remove-every-occurrence-of-sub-list-from-list-python

Update4: if you know a library to make this a one-liner, please write it as answer, since this is my preferred solution.



from How to remove every occurrence of sub-list from list

No comments:

Post a Comment