The bytearray is a built-in class in Python used to represent binary data. Similar to bytes, bytearray is also an immutable sequence, but it allows modification of its elements through indexing, making it suitable for scenarios requiring mutable binary data.

The syntax for the bytearray class is:

bytearray([source[, encoding[, errors]]])

Where:

  • source: Can be an integer, an iterable containing integers, a string, a bytes object, or a readable object
  • encoding: Required if source is a string, specifies character encoding
  • errors: Specifies error handling scheme for encoding, defaults to 'strict'

Common bytearray Operations

  • len(bytearray_object): Returns the number of bytes in bytearray_object
  • bytearray_object[index] = value: Modifies the byte at index to value
  • bytearray_object.append(value): Appends a byte value to the end
  • bytearray_object.extend(iterable): Appends all bytes from iterable to the end
  • bytearray_object.decode(encoding='UTF-8', errors='strict'): Decodes to a string
  • bytearray_object.hex(): Returns hexadecimal representation

Example Code

# Create empty bytearray
b = bytearray()

# Build bytearray by appending bytes
b.append(97) # 'a'
b.append(98) # 'b'
b.append(99) # 'c'

# Output bytearray
print(b)          # bytearray(b'abc')
print(len(b))     # 3

# Modify bytearray
b[1] = 100        # Change b[1] to 100
print(b)          # bytearray(b'adc')

# Extend with iterator
b.extend([101, 102, 103])
print(b)          # bytearray(b'adcefg')

# Convert to string
s = b.decode('ascii')
print(s)          # 'adcefg'

# Convert string to bytearray
b = bytearray('hello', 'ascii')
print(b.hex())    # '68656c6c6f'

Note that while bytearray and bytes are very similar, bytearray has slightly lower performance due to its mutability. When modification of binary data isn't required, using bytes is recommended.