Python Binary Strings vs Byte Arrays

In Python, binary strings ("bytes") and byte arrays ("bytearray") are different, although both represent sequences of bytes (0-255).


Key Differences Between "bytes" and "bytearray"

Feature "bytes" (Binary String) "bytearray" (Mutable Byte Array)
Mutability Immutable (Cannot be modified) Mutable (Can modify in-place)
Type "bytes" (Scalar) "bytearray" (Mutable Sequence)
Storage Fixed, contiguous memory block Mutable memory block
Indexing Returns an "int" (0-255) Returns an "int" (0-255)
Slicing Returns a "bytes" object Returns a "bytearray" object
Performance Faster & memory-efficient Slightly slower due to mutability
Use Cases File I/O, cryptography, sockets Byte-wise modification, memory buffer

Binary String

A "bytes" object is an immutable sequence of bytes.

Creating a "bytes" Object

binary_string = bytes([0, 1, 2, 3, 4])
print(binary_string)  # Output: b'\x00\x01\x02\x03\x04'

Immutable: Cannot Modify In-Place

binary_string[0] = 255  #  TypeError: 'bytes' object does not support item assignment

Solution: If you need to modify it, convert to "bytearray".


Byte Array

A "bytearray" is similar to "bytes", but modifiable.

Creating a "bytearray"

byte_arr = bytearray([0, 1, 2, 3, 4])
print(byte_arr)  # Output: bytearray(b'\x00\x01\x02\x03\x04')

Can Modify In-Place

byte_arr[0] = 255  # Change first byte
print(byte_arr)  # Output: bytearray(b'\xff\x01\x02\x03\x04')