Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...
like image 933
Sal Rosa Avatar asked Jul 10 '14 13:07

Sal Rosa


1 Answers

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.

like image 57
Martijn Pieters Avatar answered Nov 07 '22 21:11

Martijn Pieters