HoHo HoHo - 26 days ago 10
Python Question

Strip outer elements from list that are contained in another list

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']

Answer
def strip_list(data, to_remove):  
    idx = [i for i, v in enumerate(data) if v not in to_remove]  
    return data[idx[0]:idx[-1]+1]