Search code examples
pythonstringpython-2.7mutability

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.


Solution

  • 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.