Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 410
blue_zinc Avatar asked Jul 17 '15 20:07

blue_zinc


2 Answers

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.

like image 105
Bas Swinckels Avatar answered Sep 19 '22 18:09

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.

like image 43
Thane Brimhall Avatar answered Sep 20 '22 18:09

Thane Brimhall