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>The solution here is to use a <code>set</code>, which doesnËt requires you to save a dummy variable for each value.</p>

python