Chaining of or operator

suggest change

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):

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Common Pitfalls:
* Chaining of or operator

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
100 Common Pitfalls
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve