Why are strings immutable?

Larry Bates lbates at swamisoft.com
Mon Aug 23 17:04:22 EDT 2004


Think about it.  Since strings occupy a fixed
number of bytes in memory, a mutable string would
just be a linked list of strings.  For performance
reasons you can't require that everything in memory
gets moved around when you want to add one byte to
a string.  Multiply that by 20K and performance
would be terrible.  Since a mutable string is just
a list of strings, Python just asks the programmer
to treat it exactly like what it REALLY is.  If
you want to append lots of things to a string, build
a list and then join it into a string at the end
of processing.

Your example:

List = [ ]
for i in range(20000):
    Word = DoSomeProcessing()
    List.extend(list(Word))
Str = ''.join(List)


will work as:

words=[]
for i in xrange(20000):
    word = DoSomeProcessing()
    words.append(word)

word_string = ' '.join(words)

Notes:

1) You build the word_list by appending words that
come back frmo DoSomeProcessing().

2) If you want a space between your words you must
specify it as the character before .join() call.

3) range(20000) will create a list of length=20000
and interate over it, xrange(20000) will just create
an iterable object that returns the next number on
each sucessive call (saving both memory and the time
to create the 20K list).

4) You should stay FAR away from variables named
list or str (even though you capitalized the first
character).  list and str are python functions that
can easily get redefined by accident.  List and Str
will work, but I've seen MANY Python programmers walk
on list, str, dict by accident and later wonder why.

HTH,
Larry Bates
Syscon, Inc.

"Brent W. Hughes" <brent.hughes at comcast.net> wrote in message
news:O%rWc.171256$8_6.61890 at attbi_s04...
> Let me give two examples of where I think it would be nice to be able to
> change strings in place:
>
>
> First example:
>
> 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).  As it is, I'm thinking of
> something like this:
>
> List = [ ]
> for i in range(20000):
>  Word = DoSomeProcessing()
>  List.extend(list(Word))
> Str = ''.join(List)
>
>
> Second example:
>
> 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)
>
>





More information about the Python-list mailing list