How does Python determine if two strings are identical : <p>I've tried to understand when Python strings are identical (aka sharing the same memory location). However during my tests, there seems to be no obvious explanation when two string variables that are equal share the same memory:</p>

<pre><code>import sys
print(sys.version) # 3.4.3

# Example 1
s1 = "Hello"
s2 = "Hello"
print(id(s1) == id(s2)) # True

# Example 2
s1 = "Hello" * 3
s2 = "Hello" * 3
print(id(s1) == id(s2)) # True

# Example 3
i = 3
s1 = "Hello" * i
s2 = "Hello" * i
print(id(s1) == id(s2)) # False

# Example 4
s1 = "HelloHelloHelloHelloHello"
s2 = "HelloHelloHelloHelloHello"
print(id(s1) == id(s2)) # True

# Example 5
s1 = "Hello" * 5
s2 = "Hello" * 5
print(id(s1) == id(s2)) # False
</code></pre>

<p>Strings are immutable, and as far as I know Python tries to re-use existing immutable objects, by having other variables point to them instead of creating new objects in memory with the same value.</p>

<p>With this in mind, it seems obvious that <code>Example 1</code> returns <code>True</code>.<br>
It's still obvious (to me) that <code>Example 2</code> returns <code>True</code>.  </p>

<p>It's not obvious to me, that <code>Example 3</code> returns <code>False</code> - am I not doing the same thing as in <code>Example 2</code>?!?</p>

<p>I stumbled upon this SO question:<br>
<a href="https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce/1504742#1504742">Why does comparing strings in Python using either &#39;==&#39; or &#39;is&#39; sometimes produce a different result?</a>  </p>

<p>and read through <a href="http://guilload.com/python-string-interning/" rel="noreferrer">http://guilload.com/python-string-interning/</a> (though I probably didn't understand it all) and thougt - okay, maybe "interned" strings depend on the length, so I used <code>HelloHelloHelloHelloHello</code> in <code>Example 4</code>. The result was <code>True</code>. </p>

<p>And what the puzzled me, was doing the same as in <code>Example 2</code> just with a bigger number (but it would effectively return the same string as <code>Example 4</code>) - however this time the result was <code>False</code>?!?</p>

<p>I have really no idea how Python decides whether or not to use the same memory object, or when to create a new one.</p>

<p>Are the any official sources that can explain this behavior?</p>
