[Tutor] What does Python gain by having immutable types?

Alan Gauld alan.gauld at freenet.co.uk
Wed Mar 23 09:59:48 CET 2005


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

> He then asked
> Why is it that the sort operation modfies the original list
variable?
>
> 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.

It's related but personally I think the sort() thing is probably more
to do with saving memory and performance since a list can be very
big and returning a sorted copy could be expensive. OTOH it does
add a big inconsistency in the language and is a common gotcha
for beginners

> 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?

Quite often the only answer is "just because". Some features are
the way they are because that's Guido's pesonal preference. Others
may disagree with him but it's his language and he gets to pick
what he thinks is best - the benign dictator syndrome.

Alan G.



More information about the Tutor mailing list