bytearray behaves exactly like bytes for reading — indexing, slicing, decoding — but additionally supports in-place mutation: assigning to an index, append(), extend(), and slice assignment, all without creating a new object each time. This makes it the right choice for building up or modifying binary data incrementally, such as accumulating chunks read from a socket or file.
1Understanding Bytearray
bytearray behaves exactly like bytes for reading — indexing, slicing, decoding — but additionally supports in-place mutation: assigning to an index, append(), extend(), and slice assignment, all without creating a new object each time. This makes it the right choice for building up or modifying binary data incrementally, such as accumulating chunks read from a socket or file.
Use bytearray instead of repeatedly concatenating bytes objects when building up binary data piece by piece — like strings, bytes is immutable, so += in a loop is just as wasteful for it as it is for str.
ba = bytearray(b"Hello")
ba[0] = ord("J")
print(ba)
print(ba.decode())2Practical Example
Here is a real-world application of Bytearray showing how it is used in production Python code.
buffer = bytearray()
for chunk in [b"Hel", b"lo, ", b"World!"]:
buffer.extend(chunk)
print(bytes(buffer))3Best Practices
Follow these guidelines when working with Bytearray:
1. Use bytearray instead of bytes when the binary data needs to be modified after creation
2. Convert to bytes with bytes(ba) once mutation is done, if you need an immutable, hashable result
3. Use bytearray.extend() to append multiple bytes at once instead of looping with individual append() calls
Tip: Use bytearray instead of repeatedly concatenating bytes objects when building up binary data piece by piece — like strings, bytes is immutable, so += in a loop is just as wasteful for it as it is for str.
ba = bytearray(b"Hello")
ba[0] = ord("J")
print(ba)
print(ba.decode())