-2

Strings in python are immutable objects. Changing a string should create a new object, hence a new id.

For some reason, when I tried performing a simple string concatenation some of the time the id changed and other times it didn't. I noticed when the change I make is small it tends to not change the id but that doesn't seem like a good enough explanation. Just wondering why this is happening.

Here is a screenshot from my IDLE shell. If anyone has an explanation, I would really appreciate it :)

example of id sometimes changing, other times not

  • 1
    It's an internal implementation detail at which memory location the string will be stored. It doesn't matter, you can't predict it, you should hardly use that information for anything in the first place. – deceze Jul 13 '20 at 13:41
  • 1
    Python can, in some cases, detect that the original string isn't going to be referenced any more, and therefore the concatenation can be done in place. (I don't know the exact details. I don't *care* about the exact details, because it's not something that ever matters.) The times when this *didn't* happen in your examples, you had just typed `x` to display the string - which creates a second reference (the REPL `_` variable, referring to the previous expression), thus making this optimization inapplicable. – jasonharper Jul 13 '20 at 13:46

1 Answers1

1

This could be an optimization when the refcount for the string is exactly one, or the new string could get allocated in exactly the same location as the freshly dereferenced one. You can look through the Cpython source to figure out what's going on.

Either way, it doesn't really matter.

AKX
  • 152,115
  • 15
  • 115
  • 172