Should I use 'in' or 'or' in an if statement in Python 3.x to check a variable against multiple values?

if-statement, performance, python, python-3.x

Solution

In Python 3 (3.2 and up), you should use a set:

if x in {2, 3, 4}:

as set membership is a O(1) test, versus a worst-case performance of O(N) for testing with separate `or` equality tests or using membership in a tuple.

In Python 3, the set literal will be optimised to use a `frozenset` constant:

>>> import dis
>>> dis.dis(compile('x in {1, 2, 3}', '<file>', 'exec'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               4 (frozenset({1, 2, 3}))
              6 COMPARE_OP               6 (in)
              9 POP_TOP
             10 LOAD_CONST               3 (None)
             13 RETURN_VALUE

Note that this optimisation was added to Python 3.2 and in Python 2 or 3.0 or 3.1 you'd be better of using a tuple instead. For a small number of elements, the difference in lookup time is nullified by the set creation for each execution.

Problem

Suppose I have the following, which is the better, faster, more Pythonic method and why? ``` if x == 2 or x == 3 or x == 4: do following... ``` or : ``` if x in (2, 3, 4): do following... ```

Original source