-1

Someone please tell me there is a cleaner way to write this!? I want to remove all instances of 'Features & Benefits'. There must be a cleaner way to do this for strings in a list.

lov_headers = [x.find('displayname').text for x in soup.find_all('attributedefinition')]


if 'Part number' in lov_headers:
    lov_headers.remove('Part number')
if 'Product Features' in lov_headers:
    lov_headers.remove('Product Features')
if 'Packaging' in lov_headers:
    lov_headers.remove('Packaging')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
if 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
Sam Palmer
  • 17
  • 4

2 Answers2

1

Put what you want to remove into a set(), then use a list comprehension to filter out the results that you don't want:

to_remove = set(['Part number', 'Features & Benefits', 'Product Features', 'Packaging'])

new_list = [i for i in lov_headers if i not in to_remove]
Primusa
  • 13,136
  • 3
  • 33
  • 53
1

You can use a while loop:

while 'Features & Benefits' in lov_headers:
    lov_headers.remove('Features & Benefits')
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • 1
    The time complexity on this is not good at all. – user3483203 Apr 11 '18 at 22:26
  • 2
    Agree. But if the OP wants to remove few select headers, the time complexity does not matter. Downloading the document would take way more time than searching through a list. – DYZ Apr 11 '18 at 22:28