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's an optimisation technique called interning. CPython recognises the <a href="https://github.com/python/cpython/blob/c21f17c6e9d3218812b593f6ec5647e91c16896b/Objects/codeobject.c#L59" rel="nofollow">equal values of <strong>string constants</strong></a> and doesn't allocate extra memory for new instances but simply points to the same one (interns it), giving both the same <code>id()</code>. </p>

<p>One can play around to confirm that only constants are treated this way (simple operations like <code>b</code> are recognised):</p>

<pre><code># Two string constants
a = "aaaa"
b = "aa" + "aa"

# Prevent interpreter from figuring out string constant
c = "aaa"
c += "a"

print id(a)         # 4509752320
print id(b)         # 4509752320
print id(c)         # 4509752176 !!
</code></pre>

<p>However you can manually force a string to be mapped to an already existing one using <a href="https://docs.python.org/2/library/functions.html#intern" rel="nofollow"><code>intern()</code></a>:</p>

<pre><code>c = intern(c)

print id(a)         # 4509752320
print id(b)         # 4509752320
print id(c)         # 4509752320 !!
</code></pre>

<p>Other interpreters may do it differently. Since strings are immutable, changing one of the two will not change the other.</p>

python string