I have found myself many times,with things that I need to be all or at least one equal to something,and I would write something like that:
if a==1 and b==1:
do something
or
if a==1 or b==1:
do something
If the number of things is small its ok,but it is still not elegant.So, is there a better way for a significant number of things, to do the above?Thanks.
A conditional sentence is based on the word 'if'. There are always two parts to a conditional sentence – one part beginning with 'if' to describe a possible situation, and the second part which describes the consequence. For example: If it rains, we'll get wet.
Option 1: any / all
For the general case, have a look at any
and all
:
if all(x == 1 for x in a, b, c, d):
if any(x == 1 for x in a, b, c, d):
You can also use any iterable:
if any(x == 1 for x in states):
Option 2 - chaining and in
For your first example you can use boolean operator chaining:
if a == b == c == d == 1:
For your second example you can use in
:
if 1 in states:
Option 3: any/all without a predicate
If you only care whether the value is truthy you can simplify further:
if any(flags):
if all(flags):
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