5
a = 'This is a very long string. This is a very long string. No?'
b = 'This is a very long string. This is a very long string. No?'

print(id(a), id(b))
print(a is b)

On my computer, the results are:

4467772080 4467772080
True

As I know Python only caches short strings. But why such a long string, it still keeps only one copy? In fact, I changed it to be a very long string (even longer than 1024), a and b are still pointing to the same string object. Please correct me where I am wrong?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Vincent
  • 199
  • 1
  • 2
  • 10
  • try it in the shell instead of in a script... when they are in the same file python will cache this – Joran Beasley Jan 14 '21 at 04:22
  • 3
    Strings are immutable, so Python is free to share them or not as it sees fit. I wouldn't spend too much effort trying to understand what happens under the covers. – Mark Ransom Jan 14 '21 at 04:24
  • 1
    https://stackoverflow.com/questions/13650293/understanding-pythons-is-operator The answer with 61 upvotes has the information you are looking for – Kyle Jan 14 '21 at 04:23
  • 1
    `(a is b) == False` in my interpreter Py3.9.1 with the exact same string. The point is: what you claim doesn't always happen, and therefore if you're looking for any strange undocumented rule about interning-- it doesn't exist. – UltraInstinct Jan 14 '21 at 04:33
  • 1
    What is it you don't understand? The runtime is free to intern immutable objects. There *are no rules or guarantees about this*. What's probably happening here is that you have to immutable string literals being cached in the same block. – juanpa.arrivillaga Jan 14 '21 at 04:46
  • @JoranBeasley both Pycharm and command line, a and b are still pointing to the same object, but in interactive mode, they are different, where only a single word would be cached. – Vincent Jan 14 '21 at 05:04
  • So when there are no guarantees, many textbooks illustrate **is** operator with this example... – Vincent Jan 14 '21 at 05:09
  • 1
    @Vincent In that case you should avoid those textbooks because the authors don't know Python – Matthias Jan 14 '21 at 07:13

0 Answers0