Reputation: 545
list = [america , china, japan, mvnsangameshertet,]
I want to check whether the any string in the list contains the name sangamesh
. for example:
I can use this:
for a in list:
if "sangamesh" in a:
print True
else:
print False
But this gives me result like
False
False
False
True
I just want the output as either True
or False
I am still a beginner I tried a lot but couldnt come up with an alternative!
Upvotes: 1
Views: 89
Reputation: 1121972
Use any()
:
print any("sangamesh" in a for a in lst)
This will return True
as soon as there is any a
for which the test is True
; it won't test any more values after that.
For future reference, you could also end your loop with break
:
for a in lst:
if "sangamesh" in a:
print True
break
else:
print False
Note that the else
is now part of the for
loop instead; if you do not break out of the loop, at the end the else
suite is executed, but if you do break
, then the else
suite is skipped.
Upvotes: 6
Reputation: 133554
>>> items = ["america" , "china", "japan", "mvnsangameshertet"]
>>> any("sangamesh" in s for s in items)
True
Upvotes: 3