2

I know that strings are immutable in Python. However, the following experiment puzzles me.

First, we create a string using the str() function passing it some other object (in our case, dictionary):

>>> a = {1: 100, 2: 200}
>>> b = str(a)
>>> b
'{1: 100, 2: 200}'

Then we check its ID:

>>> id(b)
111447696

Then we "modify" the string:

>>> b = b + ' f'
>>> b
'{1: 100, 2: 200} f'

And then we check the ID of the "modified" string:

>>> id(b)
111447696

I would expect that IDs of b would be different before and after the modification, since strings are immutable, so adding ' f' to a string would produce another string, with a different ID, referring to a different location in memory. How come two different strings have the same ID?

Konstantin Popov
  • 1,546
  • 4
  • 15
  • 19
  • Can you indicate your Python version and platform? It doesn't happen for me in CPython 3.6.7 in Windows. – jdehesa Nov 15 '19 at 11:34
  • It's Windows 10 Pro, Python 3.6 – Konstantin Popov Nov 15 '19 at 11:37
  • 2
    TL;DR: don't take an object's `id` too seriously. It doesn't mean much. It's an internal detail that doesn't really tell you anything useful. In this case, the memory location is being reused because… reasons. Why shouldn't it be reused? The old string isn't needed anymore. Ask the garbage collector. – deceze Nov 15 '19 at 11:38
  • 1
    Because they have non-overlapping lifetimes, and the first one is being garbage-collected. A truer test of the immutability of strings would be `a = 'foo'` followed by `a[1] = 'x'`. – Jared Smith Nov 15 '19 at 11:44

0 Answers0