pythonstringobject

two different string object with same value in python


Let me have a string object a="ABC". Now I want to create a different object b="ABC" having both id(a) and id(b) separate. Is it possible in python?


Solution

  • This is an implementation detail. If two variables refer to the same object (a is b is true) then they have to be equal (a == b shall be true). But at least for immutable objects, Python does not specify what it does.

    The standard CPython implementation uses common ids for small integers:

    a = 1
    b = 1
    a is b   # True
    

    The rationale is that they are likely to be used in many places in the same program, and sharing a common variable saves some memory.

    It is done too for strings, when the interpreter can easily guess that they will share the same value. Example on a Python 3.6

    a = "abc"
    b = 'ab' + 'c'
    c = ''.join(chr(i) for i in range(97, 100))
    a is b      # gives True
    a is c      # gives False
    

    TL/DR: whether two equal strings share same id is an implementation detail and should not be relied on.