Next / Previous / Contents / TCC Help System / NM Tech homepage

14. The bytearray type

New in Python 2.6 is the bytearray type. Each instance is a sequence of 8-bit bytes, each of which is an unsigned integer in the range 0 <= 255. Unlike the str type, however, bytearray values are mutable: you can delete, insert, or replace arbitrary values or slices.

As with the features described in Section 13, “The bytes type”, this type is intended to ease the transition to Python 3.x versions. Use it for situations where you are handling sequences of 8-bit bytes that are not intended as textual representations, such as raw binary data.

Values of this type support almost all of the operators and methods of the str type (with the exception of .encode() and .format() methods). They also support these methods of the list type: .extend(), .insert(), .pop(), .remove(), .reverse(). You can also replace values using either integers or the b'...' (bytes) literals.

Some examples:

>>> s=bytearray('abcdef')
>>> s
bytearray(b'abcdef')
>>> type(s)
<type 'bytearray'>
>>> s[3]
100
>>> s.insert(0, b'^')
>>> s
bytearray(b'^abcdef')
>>> s.reverse()
>>> s
bytearray(b'fedcba^')
>>> s[2:6]
bytearray(b'dcba')
>>> s[2:6] = b'#'
>>> s
bytearray(b'fe#^')
>>> s[0]=63
>>> s
bytearray(b'?e#^')
>>> 

The bytearray type also has a static method named .fromhex() that creates a bytearray value from a Unicode string containing hexadecimal characters (which may be separated by spaces for legibility).

>>> ao = bytearray.fromhex(u'00 ff')
>>> ao
bytearray(b'\x00\xff')
>>> ao[1]
255