Check to see if text is contained within a variable in a list in Python

Question:

I am working with this code:

test_list = ['small_cat', 'big_dog', 'turtle']

if 'dog' not in test_list:
    output = 'Good'
else:
    output = 'Bad'

print (Output) 

Because ‘dog’ is not in the list, ‘output’ will come back with a response of ‘Good’. However, I am looking for ‘output’ to return ‘Bad’ because the word ‘dog’ is part of an item in the list. How would I go about doing this?

Asked By: Acuity

||

Answers:

You should iterate all the values in test_list

output = 'Good'
for test_word in test_list:
    if 'dog' in test_word:
        output = 'Bad'
        break

print(output)
Answered By: Tom Ron

you need to check each one in the list:

output = 'Good'
for item in test_list:
    if 'dog' in item:
        output = 'Bad'
print(output)
Answered By: César Rodrigues

any and all are super useful for this combined with a generator expression.

if any('dog' in w for w in test_list):
  ...
else:
  ...

Both any and all are very expressive of what they’re doing, and they short-circuit: as soon as the outcome is known, they stop iterating. They can be combined with conditional expressions to permit:

output = "Bad" if any('dog' in w for w in test_list) else "Good"
Answered By: Chris
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.