Python: Elegant way to store items for checking item existence in a container
<p>In the situation I encounter, I would like to define "elegant" being having <strong>1) constant O(1) time complexity</strong> for checking if an item exists and <strong>2) store only items</strong>, nothing more.</p>

<p>For example, if I use a list</p>

<pre><code>num_list = []
for num in range(10): # Dummy operation to fill the container.
    num_list += num
if 1 in num_list:
    print("Number exists!")
</code></pre>

<p>The operation "in" will take <strong>O(n) time</strong> according to [<a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">Link</a>]</p>

<p>In order to achieve constant checking time, I may employ a dictionary</p>

<pre><code>num_dict = {}
for num in range(10): # Dummy operation to fill the container.
    num_dict[num] = True
if 1 in num_dict:
    print("Number exists!")
</code></pre>

<p>In the case of a dictionary, the operation "in" costs <strong>O(1) time</strong> according to [<a href="http://stackoverflow.com/questions/17539367/python-dictionary-keys-in-complexity">Link</a>], but additional <strong>O(n) storage</strong> is required to store dummy values.  Therefore, both implementations/containers seem inelegant.</p>

<p>What would be a better implementation/container to achieve constant O(1) time for checking if an item exists while only storing the items? How to keep resource requirement to the bare minimum?</p>

<p>Normally you can't optimise both space and time together. One thing you can do is have more details about the range of data(here min to max value of num) and size of data(here it is number of times loop runs ie., 10). Then you will have two options :</p>

<ol>
<li>If range is limited then go for dictionary method(or even use array index method) </li>
<li>If size is limited then go for list method.</li>
</ol>

<p>If you choose right method then you will probably achieve constant time and space  for large sample</p>

<p>EDIT:
<strong>Set</strong>
It is a hash table, implemented very similarly the Python dict with some optimizations that take advantage of the fact that the values are always null (in a set, we only care about the keys).  Set operations do require iteration over at least one of the operand tables (both in the case of union).  <strong>Iteration isn't any cheaper than any other collection ( O(n) ), but membership testing is O(1) on average.</strong></p>

python