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, abytesobject, or a readable objectencoding: Required ifsourceis a string, specifies character encodingerrors: Specifies error handling scheme for encoding, defaults to 'strict'
Common bytearray Operations
len(bytearray_object): Returns the number of bytes inbytearray_objectbytearray_object[index] = value: Modifies the byte atindextovaluebytearray_object.append(value): Appends a bytevalueto the endbytearray_object.extend(iterable): Appends all bytes fromiterableto the endbytearray_object.decode(encoding='UTF-8', errors='strict'): Decodes to a stringbytearray_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.