Reputation: 324
I want to use this in an if statement so it would be useful if the output is a bollean expression but is there an easy way to find if string is not found in an item within a list?
e.g.
string_foo='teen'
list_foo=['one','two','three']
the problem is i need a loop to output somthing if a string is not found within an item in a list, the problem i have with doing it this way:
[print('no') if string_foo not in i for i in list_foo]
Is that for every item where string_foo isnt in i, it will print 'no' whereas i want it to only print 'no' once if string_foo isnt found within an item in list_foo
Upvotes: 1
Views: 52
Reputation: 164773
List comprehensions are to build new lists, not for their side effects. print
returns None
, so you are creating and discarding a list of None
values. This is wasteful.
any
/ all
+ generator comprehensionOne solution is to use any
with a generator comprehension:
if not any(string_foo in i for i in list_foo):
print('no')
Or equivalently with all
:
if all(string_foo not in i for i in list_foo):
print('no')
Generators / generator expressions have overheads which you may find expensive. A regular function may be more efficient:
def any_in_list(mystr, lst):
for i in lst:
if mystr in i:
return True
return False
if not any_in_list(string_foo, list_foo):
print('no')
for
/ else
loop + break
If you don't want to write a generic function, you can replicate via a for
/ else
construct with break
:
for i in list_foo:
if string_foo in i:
break
else:
print('no')
Upvotes: 4
Reputation: 233
This does what you want:
if any(x in i for i in things):
print("in it")
else:
print("not in it")
The any function returns true if any of the list items is true.
Upvotes: 0
Reputation: 11
The following should work. list_foo
is only a list of strings so you don't need to loop over each item, you can just check to see if string_foo
exists in the list or not.
if string_foo not in item:
print('no')
Upvotes: 0