2

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']
Soul Donut
  • 357
  • 3
  • 12

1 Answers1

1
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]  
dugres
  • 12,613
  • 8
  • 46
  • 51
  • lol, i am working on exactly same piece of code, this will fail if all items from input list match inside to_remove list – Skycc Nov 14 '16 at 16:09
  • 1
    change the return to return data[idx[0]:idx[-1]+1] if idx else [] , then shall be perfect – Skycc Nov 14 '16 at 16:17