Sequence Types - Bytearray

Indices and tables

Byte Array

MUTABILITY: Mutable

The mutable brother of the bytes class.

No dedicated Python syntax to create bytearray literals. Must use constructor.

  • Using the bytearray constructor to create an empty object. For example:

    >>> foo = bytearray()
    >>> foo
    bytearray(b'')
    
  • Using the bytearray constructor to create a zero-filled (i.e. null-filled) bytes objects of specified length. For example:

    >>> foo = bytearray(4)
    >>> foo
    bytearray(b'\x00\x00\x00\x00')
    
  • Using the bytearray constructor to populate a bytearray object with an iterable of integers. For example:

    >>> foo = bytearray((1, 3, 5))
    >>> foo
    bytearray(b'\x01\x03\x05')
    
  • Using the bytearray constructor to encode a string into a bytearray. This may require encoding each character into more than one byte depending on it’s code point. For example:

    >>> foo = bytearray('Ѱ', encoding='utf8')
    bytearray(b'\xd1\xb0')
    

Note

There is no method on the str to encode a string into a bytearray object like there is for encoding the str into a bytes object.

Byte Array Specific Methods

The bytearray class supports all the same methods as the bytes class.

Try it!

Try creating the following objects:

  • An empty bytearray object.
  • A bytearray object of 32 bytes, all 0.
  • A bytearray object from ASCII printable characters.
  • A bytearray object using character escape sequences.
  • A bytearray object from a tuple or list, such as [32, 48, 64].
  • A bytearray object representing the character “ɸ” in UTF-8.
  • A bytearray object representing the character “ɸ” in UTF-16.
  • Get the string given by the following bytearray object, bytearray(‘x48x65x6cx6cx6f’, encoding=’utf8’).