Search code examples
pythonlistfilterdelete-row

Remove an element in Python list with partial word in list


I have a list that looks like this and I've tried the following code and nothing seems to work. My list called "ss" looks like this and I'm trying to remove any elements with "Sheet" in list:

ss = ['14', '13', '11', '10', '9', '8', '6', '3', '2', '1', '0', '7', '4', '12', '5', 'Sheet12', 'Sheet1']

I have tried variations of this and they do nothing:

ssnew = list(filter( lambda s: not (s[0:4]=="Sheet"), ss))

or,

newss = {ss.replace("Sheet","")for x in ss}

I need my new list newss to look like this -->

newss = ['14', '13', '11', '10', '9', '8', '6', '3', '2', '1', '0', '7', '4', '12', '5'] 

Solution

  • Use a comprehension:

    >>> [i for i in ss if not i.startswith('Sheet')]
    ['14',
     '13',
     '11',
     '10',
     '9',
     '8',
     '6',
     '3',
     '2',
     '1',
     '0',
     '7',
     '4',
     '12',
     '5']