I know that Python strings are immutable, which means that
letters = "world"
letters += "sth"
would give me a different string object after the concatenation
begin: id(letters): 1828275686960
end: id(letters): 1828278265776
However, when I run a for-loop to append to a string, it turns out that the string object remain unchanged during the for-loop:
letters = "helloworld"
print("before for-loop:")
print(id(letters))
print("in for-loop")
for i in range(5):
letters += str(i)
print(id(letters))
The output:
before for-loop:
2101555236144
in for-loop
2101557044464
2101557044464
2101557044464
2101557044464
2101557044464
Apparently the underlying string object that letter points to did not change during the for-loop, which contradicts the concept that string should be immutable.
Is this some kind of optimization that Python performs under the hood?