Test if all values are in an iterable in a pythonic way

Question:

I am currently doing this:

if x in a and y in a and z in a and q in a and r in a and s in a:
    print(b)

Is there a more Pythonic way to express this if statement?

Asked By: blue_zinc

||

Answers:

if all(v in a for v in {x, y, z, q, r, s}):
    print(b)
Answered By: user1804599

Using the all function allows to write this in a nice and compact way:

if all(i in a for i in (x, y, z, q, r, s)):
    print b

This code should do almost exactly the same as your example, even if the objects are not hashable or if the a object has some funny __contains__ method. The all function also has similar short-circuit behavior as the chain of and in the original problem. Collecting all objects to be tested in a tuple (or a list) will guarantee the same order of execution of the tests as in the original problem. If you use a set, the order might be random.

Answered By: Bas Swinckels

Another way to do this is to use subsets:

if {x, y, z, q, r, s}.issubset(a):
    print(b)

REPL example:

>>> {0, 1, 2}.issubset([0, 1, 2, 3])
True
>>> {0, 1, 2}.issubset([1, 2, 3])
False

One caveat with this approach is that all of x, y, z, etc. must be hashable.

Answered By: Thane Brimhall

Converting to set, either:

if len({x, y, z, q, r, s} - set(a)) == 0:
    print b

or

t = {x, y, z, q, r, s}
if t & set(a) == t:
    print b
Answered By: thebjorn
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.