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?
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.
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.
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