11

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.

Community
  • 1
  • 1
jusperino
  • 113
  • 1
  • 1
  • 6
  • 9
    Try `set(lst).issubset([word, word1])` http://stackoverflow.com/questions/3931541/python-check-if-all-of-the-following-items-is-in-a-list – Silas Ray Sep 04 '12 at 21:19

4 Answers4

10

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()
gahooa
  • 131,293
  • 12
  • 98
  • 101
Julian
  • 3,375
  • 16
  • 27
9

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"])):
     ...
l4mpi
  • 5,103
  • 3
  • 34
  • 54
  • 5
    You have an extra set of parens in both examples. Genexps that are the sole arguments to callables can just be written `all(foo for foo in thing)`. – Julian Sep 04 '12 at 21:26
  • 1
    I know, but I prefer to write them explicitly inside parentheses. This makes it easier to see there's an iterable there and helps for refactoring... the extra parens come in handy using vim :) – l4mpi Sep 04 '12 at 21:31
2

You could do it like that:

if all(current_word in lst for current_word in (word, word1)):
  do x
tbraun89
  • 2,246
  • 3
  • 25
  • 44
1

Note: Do not ever use this. It is simply here to illustrate "yet another" capability of python.

A less efficient solution:

>>> from itertools import permutations
>>> lis=[0,1,2,3,4]
>>> (1,2) in (z for z in permutations(lis,2)) #loop stops as soon as permutations(lis,2) yields (1,2)
True
>>> (1,6) in (z for z in permutations(lis,2))
False
>>> (4,2) in (z for z in permutations(lis,2))
True
>>> (0,5) in (z for z in permutations(lis,2))
False
>>> (0,4,1) in (z for z in permutations(lis,3))
True
>>> (0,4,5) in (z for z in permutations(lis,3))
False
gahooa
  • 131,293
  • 12
  • 98
  • 101
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504