Python Language Common Pitfalls Chaining of or operator


When testing for any of several equality comparisons:

if a == 3 or b == 3 or c == 3:

it is tempting to abbreviate this to

if a or b or c == 3: # Wrong

This is wrong; the or operator has lower precedence than ==, so the expression will be evaluated as if (a) or (b) or (c == 3):. The correct way is explicitly checking all the conditions:

if a == 3 or b == 3 or c == 3:  # Right Way

Alternately, the built-in any() function may be used in place of chained or operators:

if any([a == 3, b == 3, c == 3]): # Right

Or, to make it more efficient:

if any(x == 3 for x in (a, b, c)): # Right

Or, to make it shorter:

if 3 in (a, b, c): # Right

Here, we use the in operator to test if the value is present in a tuple containing the values we want to compare against.

Similarly, it is incorrect to write

if a == 1 or 2 or 3:

which should be written as

if a in (1, 2, 3):