0

Consider the following example:

(Python 3.7.2)
>>> a = '1'
>>> id(a)
4364850768
>>> a += '2'
>>> id(a)
4365285672
>>> a += '3'
>>> id(a)
4365285672

My understanding is that when a character is appended to string a, a new object is created and the contents of the old object are copied over with the new character added. This does seem to be the case when 2 is appended as the ids change, but this does not seem to be the case when 3 is appended. I'm looking for some clarification on why the ids don't change the second time.

Jalem
  • 931
  • 1
  • 7
  • 7

1 Answers1

2

A new object is indeed created, but it looks like Python is recycling the ids. That's an implementation detail - it's best not to rely on id().

To demonstrate this, keep another copy of '12' around:

>>> id(a)
4377270112
>>> a = '1'
>>> id(a)
4376257360
>>> a += '2'
>>> id(a)
4377270152
>>> b = a 
>>> a += '3'
>>> id(a)
4377270032
>>> id(b)
4377270152
brunns
  • 2,689
  • 1
  • 13
  • 24