bytearray() is a built-in Python type that creates a mutable sequence of bytes — like bytes but writable, ideal for binary data manipulation, in-place modifications, and low-level I/O tasks. In 2026, bytearray remains essential in data science (binary parsing, image/byte streams), software engineering (network protocols, file editing, crypto), and systems programming — offering efficient, zero-copy mutations while supporting all bytes methods plus item assignment and extend/append/pop/insert/remove.
Here’s a complete, practical guide to using bytearray() in Python: creation from strings/iterables/integers, mutation & slicing, real-world patterns (earthquake binary metadata, log parsing, binary feature engineering), and modern best practices with type hints, performance, memory, and integration with Dask/Polars/pandas/NumPy.
Creating bytearray — from strings (with encoding), iterables, integers, or empty.
# From string (utf-8 by default)
ba_str = bytearray("Hello, ??!", "utf-8")
print(ba_str) # bytearray(b'Hello, \xe4\xb8\x96\xe7\x95\x8c!')
print(len(ba_str)) # 18 bytes (Unicode chars take multiple bytes)
# From list of integers (0–255)
ba_list = bytearray([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
print(ba_list) # bytearray(b'Hello, World!')
# From integer (length, initialized to 0)
ba_zero = bytearray(10)
print(ba_zero) # bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
# Empty bytearray
ba_empty = bytearray()
print(ba_empty) # bytearray(b'')
Mutation & slicing — bytearray is mutable, supports item assignment and in-place operations.
ba = bytearray(b"Hello")
ba[0] = ord('J') # change first byte
print(ba) # bytearray(b'Jello')
ba[1:3] = b'up' # slice assignment
print(ba) # bytearray(b'Jup lo')
ba.append(ord('!')) # add single byte
ba.extend(b"!!") # add multiple bytes
print(ba) # bytearray(b'Jup lo!!!')
ba.pop() # remove last byte
ba.insert(0, ord('!')) # insert at position
print(ba) # bytearray(b'!Jup lo!!')
Real-world pattern: earthquake binary metadata processing — parse, modify, extract.
# Example: binary earthquake packet (simplified)
packet = bytearray([
0x01, # version
0x07, 0x1A, # magnitude (float32 bytes)
0x23, 0x84, 0xA5, 0x40, # latitude
0xC7, 0x0F, 0xC9, 0xC0, # longitude
0x00, 0x00, 0xA0, 0x40 # depth
])
# Extract magnitude (bytes 1-4 as float)
mag_bytes = packet[1:5]
mag = struct.unpack('>f', mag_bytes)[0]
print(f"Magnitude: {mag:.2f}")
# Modify depth (bytes 9-12)
packet[9:13] = struct.pack('>f', 15.5) # set depth to 15.5 km
# Validate checksum (example)
checksum = sum(packet) % 256
print(f"Checksum: {checksum:02X}")
Best practices for bytearray in Python & data workflows. Use bytearray for mutation — when you need to modify binary data in place (e.g., protocol buffers, image pixels). Modern tip: use Polars for tabular binary data — pl.col('binary').cast(pl.Binary); Dask for distributed binary streams. Prefer bytes — when immutability is needed (hashable, safer). Use bytearray(b'abc') — from bytes literal. Use bytearray.fromhex('48656c6c6f') — from hex string. Use ba.decode('utf-8') — convert back to string. Use struct — for packing/unpacking binary structures. Add type hints — def process_binary(ba: bytearray) -> None. Use memoryview(ba) — zero-copy slicing/view. Use ba.extend()/ba.append() — grow dynamically. Avoid large bytearrays — consider mmap for huge files. Profile memory — sys.getsizeof(ba). Use ba.replace(b'old', b'new') — binary replace. Use ba.find(b'pattern') — search bytes. Use ba.hex() — hex representation (Python 3.5+).
bytearray() creates mutable byte sequences — from strings (with encoding), integers (0–255), length (zero-filled), or empty — perfect for binary manipulation, in-place edits, and low-level I/O. In 2026, use for protocol parsing, image editing, binary feature engineering, and integrate with NumPy/Dask/Polars for array-based workflows. Master bytearray, and you’ll handle binary data efficiently, mutably, and safely in any Python application.
Next time you need to modify bytes — use bytearray(). It’s Python’s cleanest way to say: “Give me bytes I can change — in place, efficiently.”