4

In Python:

>>> a = "Hello"
>>> b = "Hello"
>>> id(a) == id(b)
True

Why? Can this create a problem in a complex programs which refer to the memory locations of the object?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    In Python you generally don't *"refer to the memory locations"* - strings are immutable, so the fact that *equal* strings (same characters in the same order) might also be *identical* (same exact object) doesn't really matter. The problem comes when you rely on `str_a is str_b` in production code when you really mean `str_a == str_b`, as although identical strings are necessarily equal the reverse is not guaranteed. – jonrsharpe Oct 06 '15 at 10:36
  • 2
    You are seeing string interning, http://stackoverflow.com/questions/28329498/why-does-a-space-effect-the-identity-comparison-of-equal-strings, your example will fail with `a = "$foo"` and `b = "$foo"`, cpython will intern any strings made up of any letters, underscores and digits so becasue `$` is used the string won't be iterned, it is definitely not something to rely on – Padraic Cunningham Oct 06 '15 at 10:43

1 Answers1

6

From the Python documentation

For immutable types [like strings], operations that compute new values may actually return a reference to any existing object with the same type and value. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation...

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
xiº
  • 4,605
  • 3
  • 28
  • 39
  • strings not made up of digits, letters or an underscore will not be interned unless you do `a, b = "$foo", "$foo"` or the strings are in a function. a = `"$foo`" and `b = "$foo"` in an interpreter will not return the same id. In cpython small ints are cached so they are always going to have the same id – Padraic Cunningham Oct 06 '15 at 10:51
  • 1
    You also need to address *Can this create a problem in a complex programs which refer to the memory locations of the object* – Padraic Cunningham Oct 06 '15 at 10:55