having a list like
lst = ['hello', 'stack', 'overflow', 'friends']
how can i do something like:
if there is not an element in lst starting with 'p=' return False else return True
?
i was thinking something like:
for i in lst:
if i.startswith('p=')
return True
but i can't add the return False inside the loop or it goes out at the first element.
This will test whether or not each element of lst
satisfies your condition, then computes the or
of those results:
any(x.startswith("p=") for x in lst)
You can use builtin method any to check it any element in the list starts with p=
. Use string's startswith method to check the start of string
>>> lst = ['hello', 'stack', 'overflow', 'friends']
>>> any(map(lambda x: x.startswith('p='),lst))
>>> False
An example which should result in True
>>> lst = ['hello', 'p=stack', 'overflow', 'friends']
>>> any(map(lambda x: x.startswith('p='),lst))
>>> True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With