Possible Duplicate:
Python Check if all of the following items is in a list
So I want to test whether both word and word1 are in the list lst. Of course, I could write:
if word in lst and word1 in lst:
do x
But I wondered if I could shorten that statement to something like:
if (word and word1) in lst:
do x
Of course, that does not work, but is there anything effectively similar that will?
I tried the following, but as you can see, it does not yield the desired result.
>>> word in lst
True
>>> word1 in lst
True
>>> (word, word1) in lst
False
EDIT: Thank you for the answers, I think I have a pretty good idea of how to do this now.
The answers are correct (at least one of them is). However, if you're doing containment checks and don't care about order, like your example might suggest, the real answer is that you should be using sets, and checking for subsets.
words = {"the", "set", "of", "words"}
if words <= set_of_words:
do_stuff()
Make a list of your words and a generator expression checking if they are in the list:
words = ["word1", "word2", "etc"]
lst = [...]
if all((w in lst for w in words)):
#do something
all
checks if all values in an iterable are true. Because we use a generator this is still short-circuit optimized. Of course you can inline the list of words if it is not too big for a one-liner:
if all((w in lst for w in ["word1", "word2", "etc"])):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With