Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: return False if there is not an element in a list starting with 'p='

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.

like image 472
91DarioDev Avatar asked Nov 27 '22 08:11

91DarioDev


2 Answers

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)
like image 194
Scott Hunter Avatar answered Dec 04 '22 02:12

Scott Hunter


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
like image 38
Sohaib Farooqi Avatar answered Dec 04 '22 02:12

Sohaib Farooqi