Python Bytes And ByteArray Data Types
The focus of this tutorial is on:
bytesbytearray
Although these are not everyday data types for beginner-level applications, they become essential when dealing with low-level data such as images, audio, video, and network streams.
1. Why Do We Need Bytes?
In many programming languages, if you want to represent a collection of numbers, you typically use arrays or lists. Similarly, in Python, we use lists for general-purpose collections.
However, there are situations where:
- You want to store raw binary data
- You need values strictly in the range of 0 to 255
- You want efficient storage of byte-level information
In such cases, Python provides the bytes data type.
2. Creating a Bytes Object
The bytes object is created using the built-in bytes() function.
l = [10, 20, 30, 40]
b = bytes(l)
print(type(b)) # <class 'bytes'>
3. Iterating Over Bytes
Even though bytes represents binary data, you can still iterate over it like a sequence.
for x in b:
print(x)
10
20
30
40
This shows that each element inside the bytes object is treated as an integer.
4. Important Rule: Value Range (0 to 255)
One of the most critical rules of the bytes data type is: Each value must be in the range 0 to 255.
l = [10, 20, 30, 255]
b = bytes(l)
l = [10, 20, 30, 256]
b = bytes(l) # ValueError: bytes must be in range(0, 256)
5. Bytes Are Immutable
One of the defining characteristics of the bytes type is that it is immutable, meaning:
Once a
bytesobject is created, its content cannot be modified.
l = [10, 20, 30, 40]
b = bytes(l)
print(b[0]) # Output: 10
Now, try modifying:
b[0] = 77 # TypeError: 'bytes' object does not support item assignment
6. Introducing Bytearray
At this point, you might naturally ask:
"What if I want a mutable version of bytes?" This is exactly where bytearray comes into the picture.
7. Creating a Bytearray
Just like bytes, we use a built-in function:
l = [10, 20, 30, 40]
b = bytearray(l)
print(type(b)) # <class 'bytearray'>
8. Accessing Elements
print(b[0]) # 10
print(b[-1]) # 40
9. Value Range Rule Still Applies
Even for bytearray, values must be between 0 and 255.
l = [10, 20, 30, 256]
b = bytearray(l) # ValueError: byte must be in range(0, 256)
10. Bytearray Is Mutable
This is the key difference.
l = [10, 20, 30, 40]
b = bytearray(l)
b[0] = 77
for x in b:
print(x)
77
20
30
40
Here, the value 10 has been successfully replaced with 77.