2

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!

0

2 Answers 2

7
s = 'b'
array = ['a', 'b', 'c', 'd']

if s in array:
    del array[array.index(s):]
Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

@Elazar POITROAE (premature optimization is the root of all evil)! I would say this del is more readable than assigning to an empty list, also it works for iterables that aren't lists.
I was just about to write that the last version is the best suggested here :) . (And the del really introduce no binding in this case, so I'll remove my answer).
Works perfectly, thank you! Accepted answer due to multiple suggestions :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.