Python 2.7 store duplicate string or not
<p>Wondering if my two cases, whether Python 2.7 stores duplicate string literal <code>Hello</code>, or store one string literal <code>Hello</code>, and store only address to the string literal for duplicate to save space? Thanks.</p>

<p>My two cases shows using string literal, and using a string (<code>str</code>) variable.</p>

<pre><code>from collections import defaultdict

a = defaultdict(list)
# case 1
a[1].append("Hello")
a[2].append("Hello")

# case 2
b = "Hello"
a[3].append(b)
a[4].append(b)
</code></pre>

<p>In case 2 you are safe to assume that the same object is being referenced twice, because that's what you explicitly do. Just keep in mind that you always toss around references in Python. At the same time, the first case is a bit more complicated. CPython does optimise memory usage by caching short strings (and small numbers, too), e.g. </p>

<pre><code>In [1]: a = "Hello"

In [2]: b = "Hello"

In [3]: id(a)
Out[3]: 4448951296

In [4]: id(b)
Out[4]: 4448951296
</code></pre>

<p>In other words <code>a is b</code> returns <code>True</code>. But this is not something you can rely on, because the size threshold may differ between different versions and builds. </p>

<pre><code>In [8]: c = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks"

In [9]: d = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks"

In [10]: c is d
Out[10]: False
</code></pre>

python python-2.7