Python - Data Type String Immutability


Every string operation produces a new string.

Strings are immutable in Python-they cannot be changed in place after they are created.

You can never overwrite the values of immutable objects.

You can't change a string by assigning to one of its positions.

You can build a new one and assign it to the same name.

S = 'test'        # Make a 4-character string, and assign it to a name 
>>> S[0] = 'z'    # Immutable objects cannot be changed 
...error text omitted... 
TypeError: 'str' object does not support item assignment 

S = 'z' + S[1:]        # But we can run expressions to make new objects 

Every object in Python is classified as either immutable or mutable.

Numbers, strings, and tuples are immutable.

Lists, dictionaries, and sets are mutable.

Immutability ensures that an object remains constant throughout your program.

Mutable objects' values can be changed at any time and place regardless whether you expect it or not.

You can change text-based data in place if you either expand it into a list of individual characters and join it back together with nothing between.

You can also use bytearray type available.


S = 'this' 
L = list(S)         # Expand to a list: [...] 
print( L )

L[1] = 'c'          # Change it in place 
print( ''.join(L) ) # Join with empty delimiter 
# from   w  w w  . ja va 2  s .c o  m

B = bytearray(b'test') # A bytes/list hybrid (ahead) 
B.extend(b'')      # 'b' needed in 3.X, not 2.X 
print( B )             # B[i] = ord(c) works here too 
print( B.decode() )    # Translate to normal string


The bytearray supports in-place changes for text, but only for text whose characters are all at most 8-bits wide (e.g., ASCII).

Related Topic