The fact that the id
s were the same implies that they are pointing on the same object.
String in Python is immutable, you can’t assign to it’s indexes values.
Immutability means that we can change the original object:
# List is mutable
l = [1, 2, 3]
# That's OK
l[0] = 5
# String is NOT mutable
s="123"
# That's NOT OK - and WON'T work!
s[0] = '5'
The following assignment means that we create another pointer, to the same string:
S = "Taxi"
T = "Zaxi"
# The following line of code will cause 'S' point on 'T' string
# The string referenced by 'S' before has not changed! (and not available)
S = T
# Assertion will pass, as we changed S to point on T, now they point on same string
assert id(S) == id(T)
The fact that strings are immutable makes it memory-inefficient to generate new strings based on existing strings.
In C#, where strings are immutable too, there is a class called StringBuilder
which mitigates this in-efficiency.
On other alternatives to StringBuilder
in Python read more in this great thread.
4
solved How is string is immutable and I can replace it in ‘python’ [closed]