A friend recently asked my this didn't modify his original string variable

s1="this is a string"
s1.replace("is a", "is a short")
"this is a short string"
print s1
"this is a string"


After showing him to change it to this
s1 = s1.replace("is a", "is a short")
print s1
"this is a short string"


He then asked
Why is it that the sort operation modfies the original list variable?

l1=[]
l1.append(3)
l1.append(44)
l1.append(1)
l1.append(22)
l1
[3, 44, 1, 22]
l1.sort()
l1
[1, 3, 22, 44]

I don't know, but I think it has something to do with strings being
immutable, whiles lists are mutable.

So, other than the non-informative answer " because that's how the
language was written" are there any other reasons how Python benefits
from immutable types?

Does it really matter if s1 is a different object, so long as it
contains the expected
modified string?

The list variable is the same object, and contains the sorted list, so
why bother with the complexity of immutable types at all?
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to