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?

4
  • Can you indicate your Python version and platform? It doesn't happen for me in CPython 3.6.7 in Windows. Commented Nov 15, 2019 at 11:34
  • It's Windows 10 Pro, Python 3.6 Commented Nov 15, 2019 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. Commented Nov 15, 2019 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'. Commented Nov 15, 2019 at 11:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.