How is python storing strings so that the 'is' operator works on literals?
<p>In python </p>

<pre><code>&gt;&gt;&gt; a = 5
&gt;&gt;&gt; a is 5
True
</code></pre>

<p>but </p>

<pre><code>&gt;&gt;&gt; a = 500
&gt;&gt;&gt; a is 500
False
</code></pre>

<p>This is because it stores low integers as a single address. But once the numbers begin to be complex, each int gets its own unique address space. This makes sense to me.</p>

<blockquote>
  <p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. </p>
</blockquote>

<p>So now, why does this not apply to strings? Are not strings just as complex as large integers (if not moreso)?</p>

<pre><code>&gt;&gt;&gt; a = '1234567'
&gt;&gt;&gt; a is '1234567'
True
</code></pre>

<p>How does python use the same address for all string literals efficiently? It cant keep an array of every possible string like it does for numbers.</p>

<p>It doesn't store an array of all possible strings, instead it has a hash table which point to memory addresses of all currently declared strings, indexed by the hash of the string.</p>

<p>For example</p>

<p>when you say <code>a = 'foo'</code>, it first hashes the string <code>foo</code> and checks if an entry already exists in the hash table. If yes, then variable <code>a</code> now references that address. </p>

<p>If no entry is found in the table, python allocates memory to store the string, hashes <code>foo</code> and adds an entry in the table with the address of the allocated memory.</p>

<p>See:</p>

<ol>
<li><a href="http://stackoverflow.com/questions/2987958/how-is-the-is-keyword-implemented-in-python">How is the &#39;is&#39; keyword implemented in Python?</a></li>
<li><a href="https://en.wikipedia.org/wiki/String_interning" rel="nofollow">https://en.wikipedia.org/wiki/String_interning</a></li>
</ol>

python string