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

Time:12-01

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?

CodePudding user response:

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)

CodePudding user response:

you need to check each one in the list:

output = 'Good'
for item in test_list:
    if 'dog' in item:
        output = 'Bad'
print(output)

CodePudding user response:

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"
  • Related