Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if multiple objects are in a list using one "in" statement (Python) [duplicate]

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.

like image 304
jusperino Avatar asked Sep 04 '12 21:09

jusperino


2 Answers

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()
like image 198
Julian Avatar answered Sep 20 '22 15:09

Julian


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"])):
     ...
like image 20
l4mpi Avatar answered Sep 23 '22 15:09

l4mpi