Loop through a list of strings and remove all items after a specific list item(i) where i can be a or b or c

Viewed 52

Search through the list and remove everything else inclusive and after either Audi or Mazda or Suzuki. Please note Only one of the 3 can be in the list but not two or all of them. Just one of them

First Scenario: if it's Audi, Give a list (list items are random):

lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]

Expected result:

new_lst = ["Nissan","Chevrolet"]

Scenario 2 : If it's Suzuki.

Expected result

lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru","Suzuki","Mitsubishi"]

new_lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru"]

etc etc

2 Answers

You can use itertools.takewhile to crate a new list and 'break' out at the appropriate point

>>> from itertools import takewhile
>>> lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]
>>> list(takewhile(lambda x: x != "Audi", lst))
['Nissan', 'Chevrolet']

Use list slicing with list.index

Ex:

lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]
print(lst[:lst.index("Audi")])

lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru","Suzuki","Mitsubishi"]
print(lst[:lst.index("Suzuki")])

Output:

['Nissan', 'Chevrolet']
['Nissan', 'Chevrolet', 'Mercedes', 'BMW', 'Subaru']
Related