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>As suggested by multiple people, go for reability.</p>

<p>performance wise there is a difference, the <code>in</code> operator on sets has an average lookup time of O(1), while for lists it's O(n). You can find this <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">here</a>.</p>

<p>In your case where the list of possibilities is limited you will hardly notice a difference. However, once this list becomes very large (talking about millions), you can notice a difference.</p>

<p>A simple example can show this: For sets:</p>

<pre><code>operation = 9999999
lookupSet = {i for i in range(0,10000000)}
%timeit operation in lookupSet
&gt;&gt; 10000000 loops, best of 3: 89.4 ns per loop
</code></pre>

<p>where with lists:</p>

<pre><code>operation = 9999999
lookupList =  [i for i in range(0,10000000)]
%timeit operation in lookupList
&gt;&gt; 10 loops, best of 3: 168 ms per loop
</code></pre>

python performance python-3.x