Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What effects do parentheses have on the 'or' operator in Python?

Tags:

python

Is there a difference between these two statements in python:

if tag == ('/event' or '/organization' or '/business'):

and

if tag == '/event' or '/organization' or '/business':
like image 893
startuprob Avatar asked Nov 28 '22 09:11

startuprob


2 Answers

They are both wrong. What you need is:

if tag == '/event' or tag == '/organization' or tag == '/business':

or:

if tag in ['/event', '/organization', '/business']:
like image 61
interjay Avatar answered May 29 '23 07:05

interjay


The proper solution is

if tag in ('/event', '/organization', '/business'):

It not only uses the in operator which is perfect for this purpose but also uses a tuple (immutable) so the python interpreter can optimize it better than a (mutable) list.

Benchmark showing that tuples are faster than lists:

In [1]: import timeit
In [2]: t1 = timeit.Timer('"b" in ("a", "b", "c")')
In [3]: t2 = timeit.Timer('"b" in ["a", "b", "c"]')

In [4]: t1.timeit(number=10000000)
Out[4]: 0.7639172077178955

In [5]: t2.timeit(number=10000000)
Out[5]: 2.240161895751953
like image 42
ThiefMaster Avatar answered May 29 '23 09:05

ThiefMaster