Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python += operator make string mutable?

When I try to modify string using += operator, and use id() method to check object's identity, string seems to be mutable. Did someone face with such a weird python behaviour?

a = '123'

print id(a)
# 89806008

a += '1'

print id(a)
# 89245728

a += '1'

print id(a)
# 89245728

print a

# '12311'

Using a = a + '1' doesnt have the same effect, and change the string id.

like image 980
bbrutall Avatar asked Jan 02 '23 23:01

bbrutall


1 Answers

If you were correct about this string being mutable, then adding

b = a

before your second a += '1' should not have any effect on your output. But it does.

The reason is that because the string a had before the "increment" is no longer used anywhere, the id can be re-used. But by assigning that string to b, it now is used somewhere, and the new string for a can't re-use that id.

like image 194
Scott Hunter Avatar answered Jan 05 '23 17:01

Scott Hunter