2

in addition to the answers provided here

For example :

q = "asdasdasdsadsadsadsadsadsadsadsadsad"
a = "asdasdasdsadsadsadsadsadsadsadsadsad"

>>> a is q
True

even though the strings are long(way longer than 4 characters), python still points to the same object in memory no matter how many times i concatenate "asd", but...

..if i add,lets say "e", that makes the unique characters 4 (a,s,d and e) and python now creates a value object in heap.

q = "asdasdasdsadsadsadsadsadsadsadsadsade"
a = "asdasdasdsadsadsadsadsadsadsadsadsade"

>>> a is q
False

Interesting.

Can someone elaborate on this?

Edit:

Now it is True, but if I add a special character in both variables then it returns False

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Some general background here, but it doesn't cover your specific observation: https://stackoverflow.com/questions/15541404/python-string-interning – slothrop Apr 29 '23 at 12:49
  • 1
    I can reproduce both your examples on Python 3.11. But if I remove the `*` character from the second example, `a is q` is True. I wonder if something special happens for alphabetic characters only? – slothrop Apr 29 '23 at 12:50
  • This is implementation dependent. There is no requirement it should be like that. – trincot Apr 29 '23 at 13:03
  • @slothrop i removed the asterisks from the example.In my side.Python output was True. Now i rerun it it is False. – Spyros Kappalamda Apr 29 '23 at 15:00
  • @slothrop Indeed i also tried it with non alphanumeric characters and it returns False. Also, now i always get True with alphanumeric characters and I cannot replicate. duh. Python 3.11.2 – Spyros Kappalamda Apr 29 '23 at 15:06
  • 1
    Interesting - I consistently get `True` for your revised second example (CPython 3.11.0 on Windows - and the same on 3.10.5) – slothrop Apr 29 '23 at 15:06
  • @trincot Please, elaborate – Spyros Kappalamda Apr 30 '23 at 17:16
  • See answers in dupe-reference. – trincot Apr 30 '23 at 17:25
  • 1
    @SpyrosKappalamda a link from that dupe question took me here - http://guilload.com/python-string-interning/ Note the part about "all_name_chars": basically any string with a non-alphanumeric char (except underscore) won't be interned. That page is from the Python 2 days - the relevant bit of the CPython source is now here: https://github.com/python/cpython/blob/654d44b3a4d3ee4d92b690668aa5189acf4f9d8f/Objects/codeobject.c#L151 – slothrop Apr 30 '23 at 20:06

0 Answers0