Reputation: 3431
I have a simple question, if I have an array of strings in python: ['a', 'b', 'c', 'd'] is there a way that I can compare another string and if it exists in the array delete that value and everything after it? I'm new to python and I'm not too familiar with the syntax but pseudocode:
s = 'b'
array = ['a', 'b', 'c', 'd']
if b exists in array
remove b and elements after
so the new array would simply be ['a']. Any help would be much appreciated!
Upvotes: 2
Views: 5493
Reputation: 18521
s = 'b'
array = ['a', 'b', 'c', 'd']
if s in array:
del array[array.index(s):]
Upvotes: 7
Reputation: 11060
Alternatives:
from itertools import takewhile
array = takewhile(lambda x: x != "b", array)
# then if array must be a list (we can already iterate through it)
array = list(array)
or
if "b" in array:
del array[array.index("b"):]
or
try:
del array[array.index("b"):]
except ValueError:
# "b" was not in array
pass
Upvotes: 2