Python Strinh Immutability Broken!

Terry Reedy tjreedy at
Wed Aug 27 04:25:04 CEST 2008

Hendrik van Rooyen wrote:

> Terry Reedy:

>> Which essentially is the bytearray type of 3.0.
> How does it differ from plain old array.array(b,”The quick brown fox”)?

The typecode must be quoted as 'b'.
In 3.0, strings become unicode, so an added b prefix is needed.
 >>> import array
 >>> a = array.array('b', b'fox')
 >>> b=bytearray(b'fox')

As to your question: the underlying implementation of bytearrays is 
based on that of array('b')s. Bytearrays are built in so no import is 
needed.  Dir() shows that both have all sequence methods, but arrays 
also have list methods, while bytearrays also have string/bytes methods.

They have different representations
 >>> a
array('b', [102, 111, 120])
 >>> b

Bytearrays, like lists/arrays, have the __setitem__ method needed to 
make them mutable via indexing.

 >>> a[0]=ord(b'b')
 >>> b[0]=ord(b'b')
 >>> a
array('b', [98, 111, 120])
 >>> b

Arrays can extend bytearrays but not vice versa.  This may be a glitch.

 >>> c = a + b
Traceback (most recent call last):
   File "<pyshell#24>", line 1, in <module>
     c = a + b
TypeError: can only append array (not "bytearray") to array
 >>> c = b + a
 >>> c

Either can initialize the other

 >>> d = array.array('b',c)
 >>> d
array('b', [98, 111, 120, 98, 111, 120])
 >>> c=bytearray(d)
 >>> c

So if one does more that the common mutable sequence operations, there 
is a basis for choosing one or the other.

Terry Jan Reedy

More information about the Python-list mailing list