Search code examples
pythonlistloopsany

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.


Solution

  • 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)