Why are strings immutable?

Hallvard B Furuseth h.b.furuseth at usit.uio.no
Mon Aug 23 22:11:36 CEST 2004


Brent W. Hughes wrote:

> Let me give two examples of where I think it would be nice to be able to
> change strings in place:

Sure, it would be nice sometimes.
But immutable strings provide many nice advantages too.

> I want to add about 20,000 words to the end of a string, something like
> this:
> 
> Str = [ ]
> for i in range(20000):
>  Word = DoSomeProcessing()
>  Str += Word
> 
> I'd actually like to say Str.extend(Word).

If you are doing a lot of that with the string, does it need to be a
single string?  I've just speeded up a program significantly by changing
  string_var = ...
  string_var += ...
  string_var += ...
  ...
to
  array_var = ['string']
  array_var.append(...)
  array_var.append(...)
  ...
  result = "".join(array_var)
(Well, because of how the data was structured I actually used a dict
which was unpacked to a list comprehension which was joined to a string,
but it still speeded things up.)

You might also speed things up with
  append_string = array_var.append
  append_string(...)
if it is too slow, since that saves a lot of attribute lookups.  But
don't make your code more unreadable like that unless it _is_ too slow.

> I would like to reverse a string containing about 120,000 characters.  I'd
> like to do it in place, but I'm planning to do something like this:
> 
> List = list(Str)
> List.reverse()
> Str = ''.join(List)

import array
a = array.array('c', Str)
a.reverse()
Str = a.tostring()

Still needs two new objects, but at least that's a lot fewer than your
list.

-- 
Hallvard



More information about the Python-list mailing list