Is there a way to simplify "if x == 1 and y == 2:"

914 views Asked by At

Is there a way to simplify:

if x == 1 and y == 2 and z == 3:

if x == 1 and y == 1 and z == 1:

if x == 1 or y == 2 or z == 3:


if x == 1 or x == 2 is simplified as if x in [1, 2]:

1

There are 1 answers

2
jonrsharpe On BEST ANSWER

One of your examples is not like the others. The and form can easily be simplified:

if x == 1 and y == 2 and z == 3:

becomes:

if (x, y, z) == (1, 2, 3):

However, the or form can't be made any neater. It could be rewritten as:

if any(a == b for a, b in zip((x, y, z), (1, 2, 3))):

but that's hardly "simplified".