What effects have parentheses for the "or" operator in Python?

Is there any difference between these two operators in python:

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

and

 if tag == '/event' or '/organization' or '/business': 
+4
source share
5 answers

They are both wrong. What you need:

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

or

 if tag in ['/event', '/organization', '/business']: 
+12
source

Correct solution

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

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

Test 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 
+12
source

I will not work the way you want it either. Do you want to:

 if tag in ['/event', '/organization', '/business']: 
+3
source

The first is identical if tag == 'event' . The second is identical if tag == '/event' or True or True , which is always true.

+2
source

('/event' or '/organization' or '/business') evaluates to '/event' , so the first thing is equivalent if tag == '/event':

tag == '/event' or '/organization' or '/business' equivalent to (tag == '/event') or '/organization' .

Actually you want:

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

All Articles