[Tutor] strings features versus lists

Mats Wichmann mats at wichmann.us
Fri Nov 22 18:29:50 EST 2019


On 11/22/19 1:01 PM, Joel Goldstick wrote:
> On Fri, Nov 22, 2019 at 2:57 PM Patrick Frank <sfsoc at gmx.net> wrote:
>>
>> Hello,
>>
>> at the moment I mainly learn basics from the excellent book "Think
>> Python". As I walked through chapter 10 (which is about lists) I
>> wondered why are strings immutable? I would like to understand this
>> design decision.
>>
>> Thanks in advance,
>> P.

> 
> I'm not a language maven, like some others here, but the first thing
> that comes to mind for me is that immutable strings can be used as
> keys for dictionaries.

That's such an old decision the full rationale might be lost in the 
mists of time.

Simplicity, reliability, predicatbility are pretty much what I've heard. 
  The use as a dictionary key is absolutely part of the equation; 
dictionaries as key-value pairs accomplish effective lookups by hashing 
the key, and if the key can change (mutable), you could no longer use 
the hash of the key to reliably find the location of that entry. 
Dictionaries could have been designed differently, of course, but as you 
can see a different choice for strings would have cascading effects.

The core of Python is written in C, which is notorious for problems with 
strings. Actually, it doesn't have string as a fundamental data type, it 
uses arrays of characters and has a long history of issues with "string" 
operations; Python went a different way by saying it will always make a 
new string, not try to modify things in place.




More information about the Tutor mailing list