Python provides a mutable sequence of bytes called a byte array. Unlike immutable bytes objects, byte arrays allow in‑place modifications, making them ideal for low‑level data manipulation, file I/O, and network operations.
1. What is a Byte Array?
A byte array is a mutable sequence of integers (0–255) representing raw 8‑bit data. They are useful when you need to modify binary data in place.
2. Creating Byte Arrays
You can create byte arrays in several ways:
From a Bytes Literal:
my_bytearray = bytearray(b'Hello')
print(my_bytearray) # Output: bytearray(b'Hello')From a List of Integers:
numbers = bytearray([72, 101, 108, 108, 111])
print(numbers) # Output: bytearray(b'Hello')From a String with Encoding:
text = "Hello, World!"
byte_array = bytearray(text, 'utf-8')
print(byte_array) # Output: bytearray(b'Hello, World!')3. Accessing Byte Array Elements
Access individual elements by their index. Note that each element is an integer (0–255).
data = bytearray(b'Python')
print(data[0]) # Output: 80 (ASCII for 'P')
print(chr(data[0])) # Output: P4. Byte Array Slicing
Like lists, byte arrays support slicing to obtain sub‑sequences.
data = bytearray(b'abcdef')
print(data[1:4]) # Output: bytearray(b'bcd')5. Byte Array Mutability
Byte arrays are mutable. You can change individual byte values using their index.
data = bytearray(b'hello')
data[0] = ord('H') # Replace 'h' with 'H'
print(data) # Output: bytearray(b'Hello')6. Byte Array Operations
Byte arrays support several operations similar to lists:
Length (len()):
data = bytearray(b'Hello')
print(len(data)) # Output: 5Concatenation (+):
a = bytearray(b'Hello, ')
b = bytearray(b'World!')
c = a + b
print(c) # Output: bytearray(b'Hello, World!')Repetition (*):
data = bytearray(b'Ha!')
print(data * 3) # Output: bytearray(b'Ha!Ha!Ha!')Membership (in):
Since each element is an integer, you can test for membership by checking the byte value.
data = bytearray(b'Hello')
print(101 in data) # Output: True # 101 is ASCII for 'e'7. Byte Array Methods
Several built‑in methods let you modify byte arrays in place:
append(x)
Adds a single integer (0–255) to the end of the byte array.
data = bytearray(b'Hi')
data.append(33) # 33 is ASCII for '!'
print(data) # Output: bytearray(b'Hi!')extend(iterable)
Appends multiple elements from another iterable or byte array.
data = bytearray(b'Hello')
data.extend([32, 87, 111, 114, 108, 100]) # Appends ' World'
print(data) # Output: bytearray(b'Hello World')insert(index, x)
Inserts a byte (integer 0–255) at the specified index.
data = bytearray(b'Hllo')
data.insert(1, ord('e'))
print(data) # Output: bytearray(b'Hello')pop([index])
Removes and returns the byte at the given index (default is the last element).
data = bytearray(b'Hello')
removed = data.pop()
print(removed) # Output: 111 # ASCII for 'o'
print(data) # Output: bytearray(b'Hell')remove(x)
Removes the first occurrence of the specified byte value.
data = bytearray(b'Heelllo')
data.remove(101) # Removes the first 101 (ASCII for 'e')
print(data) # Output: bytearray(b'Helllo')decode(encoding)
Converts the byte array into a string using the specified encoding.
data = bytearray(b'Python')
text = data.decode('utf-8')
print(text) # Output: Python8. Converting Between Byte Arrays and Bytes
You can convert between mutable byte arrays and immutable bytes objects.
Byte Array to Bytes:
data = bytearray(b'example')
immutable_bytes = bytes(data)
print(immutable_bytes) # Output: b'example'Bytes to Byte Array:
immutable_bytes = b'example'
data = bytearray(immutable_bytes)
print(data) # Output: bytearray(b'example')9. Unpacking Byte Arrays
You can unpack byte arrays into individual variables just like lists.
data = bytearray(b'ABCD')
a, b, c, d = data
print(a, b, c, d) # Output: 65 66 67 68You can also use the asterisk (*) to capture multiple bytes:
data = bytearray(b'12345')
first, *middle, last = data
print(first) # Output: 49 (ASCII for '1')
print(middle) # Output: [50, 51, 52] (ASCII for '2', '3', '4')
print(last) # Output: 53 (ASCII for '5')10. When to Use Byte Arrays
- Use byte arrays when you need a mutable sequence of bytes for binary data manipulation.
- They are ideal for file operations, network communications, and in‑place modifications of binary buffers.
- Use immutable
byteswhen you require a hashable object for dictionary keys or when data should remain constant.
In summary, Python byte arrays are a powerful tool for handling binary data, offering mutability and a rich set of operations. They are ideal for applications where you need to process and modify raw byte data efficiently.
