I'm trying to remove all outer elements of a list that are contained in a second list, while keeping ones that may be 'sandwiched' inside. I know how to take the complement of the intersection of two sets, but here I just want to remove all beginning and trailing elements. So far I've come up with the following, but it feels clunky:
def strip_list(l, to_remove):
while l[0] in to_remove:
l.pop(0)
while l and l[-1] in to_remove:
l.pop(-1)
return l
mylist = ['one', 'two', 'yellow', 'one', 'blue', 'three', 'four']
nums = ['one', 'two', 'three', 'four']
strip_list(mylist, nums)
# > ['yellow', 'one', 'blue']