Is Python string immutable?

Scott David Daniels scott.daniels at
Sat Dec 3 16:37:49 CET 2005

Steve Holden wrote:
> could ildg wrote:
>> Will string operation in python also leave some garbage? I implemented 
>> a net-spider in python which includes many html string procession. 
>> After it running for sometime, the python exe eats up over 300M 
>> memory. Is this because the string garbages?
> If you create garbage in a Python program it will normally be collected 
> and returned to free memory

So far so good -- true for all Pythons.

> by the garbage collector, which should be run when memory is exhausted
 > in preference to allocating more memory.

True for Jython, probably true for IronPython (I don't know IronPython
details), definitely not true for CPython.  CPython recycles simply
held memory as the last reference goes away.  In CPython, only when
memory is held in (or by) cyclic structures is the garbage collector
needed to come in and do recycling work.

> Additional memory should therefore only be claimed when garbage 
> collection fails to return sufficient free space.
> If cyclic data structures are created (structures in which components 
> refer to each other even though no external references exist) this could 
> cause problems in older versions of Python, but nowadays the garbage 
> collector also takes pains to collect unreferenced cyclic structures.

By older he means substantially older.  If you have a Python >= 2.0 you
have no worries, the collector does cycles.  It needs to get to 2.2 or
so before weakrefs are handled correctly.

     * Python 2.4.2 (September 28, 2005)
     * Python 2.4 (November 30, 2004)
     * Python 2.3.5 (February 8, 2005)
     * Python 2.2.3 (May 30, 2003)
     * Python 2.1.3 (April 8, 2002)
     * Python 2.0.1 (June 2001)
     * Python 1.6.1 (September 2000)
     * Python 1.5.2 (April 1999)

--Scott David Daniels
scott.daniels at

More information about the Python-list mailing list