Python 3 - Bytes

Updated: 2021-11-19


  • 8-bit integer, in the range 0 to 255
  • raw, no meaning; meaning depend on encoding.

Immutable vs Mutable

  • bytes is an immutable array of bytes (PyString)
  • bytearray is a mutable array of bytes (PyBytes)
  • memoryview is a bytes view on another object (PyMemory)

bytes literal: b'...'

  • str objects: hold character data
  • bytes objects: hold raw bytes

Indexing returns a integer:

>>> a = b'asdf'
>>> a
>>> a[0]

while str returns a character:

>>> b = 'asdf'
>>> b
>>> b[0]
  • Assigning or comparing an object that is not an integer to an element causes a TypeError exception.
  • Assigning an element to a value outside the range 0 to 255 causes a ValueError exception.