Python best practice: series of "or"s or "in"?
<p>I am working on a <a href="https://github.com/johnroper100/CrowdMaster/pull/17" rel="nofollow">project</a> where a question came up about the following line:</p>

<pre><code>a == "EQUAL" or a == "NOT EQUAL" or a == "LESS" or a == "GREATER"
</code></pre>

<p>I proposed a change to make it "simpler" like so:</p>

<pre><code>a in ["EQUAL", "NOT EQUAL", "LESS", "GREATER"]
</code></pre>

<p>What would be considered best practice and what would be best for performance? This is for user interface code that gets updated frequently so minor performance improvements could be noticeable. I know the first example will "fail fast" if any were found, and I am assuming that the second would as well. </p>

<p>Furthermore, wouldn't it be even faster to use a dict like:</p>

<pre><code>a in {"EQUAL", "NOT EQUAL", "LESS", "GREATER"}
</code></pre>

<p>...so that a list wouldn't need to be constructed?</p>

<p>The only thing PEP-8 says (that I could find):</p>

<blockquote>
  <p>...code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code...</p>
  
  <p>However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best.</p>
</blockquote>

<p>Obviously in your case it's better to use <code>in</code> operator. It's just much more readable.</p>

<p>In more complex cases when it's not possible to use <code>in</code> operator, you may use <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all</code></a> and <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any</code></a> functions:</p>

<pre><code>operations = {'EQUAL', 'NOT EQUAL', 'LESS', 'GREATER'}
condition1 = any(curr_op.startswith(op) for op in operations)

condition2 = all([
    self.Operation == "EQUAL",
    isinstance(self.LeftHandSide, int),
    isinstance(self.RightHandSide, int),
])
</code></pre>

python performance python-3.x