HoHo HoHo - 1 year ago 80
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:
while l and l[-1] in to_remove:
return l

mylist = ['one', 'two', 'yellow', 'one', 'blue', 'three', 'four']
nums = ['one', 'two', 'three', 'four']
strip_list(mylist, nums)
# > ['yellow', 'one', 'blue']

Answer Source
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]  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download