Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 store duplicate string or not

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

My two cases shows using string literal, and using a string (str) variable.

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)
like image 417
Lin Ma Avatar asked Apr 05 '26 21:04

Lin Ma


1 Answers

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.

In [1]: a = "Hello"

In [2]: b = "Hello"

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

In [4]: id(b)
Out[4]: 4448951296

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

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
like image 79
Eli Korvigo Avatar answered Apr 08 '26 19:04

Eli Korvigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!