4

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.

91DarioDev
  • 1,612
  • 1
  • 14
  • 31

6 Answers6

10

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • 4
    Why the list comprehension inside `any` instead of a generator comprehension `any(x.startswith("p=") for x in lst)`? – Patrick Haugh Jan 20 '18 at 17:09
  • 1
    I removed the list comprehension. You were wasting memory and tests. With a generator expression `any()` can *short-circuit the loop*; when the first element passes the test there is no need to test everything that follows any more. – Martijn Pieters Jan 05 '20 at 01:01
5

use any conditions to check all the elements in a list with the same condition:

lst = ['hello','p=15' ,'stack', 'overflow', 'friends']
return any(l.startswith("p=") for l in lst)
mehrdadep
  • 972
  • 1
  • 15
  • 37
5

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
Sohaib Farooqi
  • 5,457
  • 4
  • 31
  • 43
4

I suggest using an iterator such as

output = next((True for x in lst if x.startswith('p=')),False)

This will output True for the first lst element that starts with 'p=' then stop searching. If it reaches the end without finding 'p=', it returns False.

jshrimp29
  • 588
  • 6
  • 8
3

Well, let's do it in two parts:

First of all, you could create a new list in which each element would be a string containing only the first 3 characters of each original item. You can use map() to do so:

newlist = list(map(lambda x: x[:2], lst))

Then, you only need to check if "p=" is one of those elements. That would be: "p=" in newlist

Combining both of the above in a function with a single statement should look like this:

def any_elem_starts_with_p_equals(lst):
    return 'p=' in list(map(lambda x: x[:2], lst))
kyriakosSt
  • 1,754
  • 2
  • 15
  • 33
3

Try this

if len([e for e in lst if e.startwith("p=")])==0: return False
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44