Python syntax for "if a or b or c but not all of them"

Chris Wilson picture Chris Wilson · May 13, 2013 · Viewed 220.1k times · Source

I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.)

What's the ideal syntax for something like:

if a and (not b or not c) or b and (not a or not c) or c and (not b or not a):

?

Answer

defuz picture defuz · May 13, 2013

How about:

conditions = [a, b, c]
if any(conditions) and not all(conditions):
   ...

Other variant:

if 1 <= sum(map(bool, conditions)) <= 2:
   ...