I've noticed that when you concatenate strings in python, sometimes the id()
of the variable does not change, which means the str
object changed.
Let me explain:
>>> a = 'a'
>>> id(a)
2844964047152
>>> a+='b'
>>> id(a)
2844971374576
>>> a+='c'
>>> id(a)
2844971374576
At first a
is (...152) and concatenating 'b' creating a new 'ab' object (...576) which a
will reference. This is the expected behavior.
But then, concatenating 'c' changes the same object ("...576") to 'abc'?
I'd much appreciate it if someone could explain this.
Edit:
this question was marked duplicate with Aren't Python strings immutable? Then why does a + " " + b work? although it's completely different