Bytearray
Understanding Bytearray
A bytearray in Python is a mutable sequence of integers in the range 0 <= x < 256. It's essentially a modifiable version of the bytes object.
Creating a Bytearray
Similar to bytes, bytearrays can be created in several ways:
- From a string:
Python
text = "Python is interesting."
byte_array = bytearray(text, 'utf-8')
print(byte_array) # Output: bytearray(b'Python is interesting.')
- From an iterable of integers:
Python
byte_array = bytearray([65, 66, 67])
print(byte_array) # Output: bytearray(b'ABC')
- From a given size:
Python
byte_array = bytearray(5)
print(byte_array) # Output: bytearray(b'\x00\x00\x00\x00\x00')
Modifying Bytearrays
Unlike bytes, bytearrays can be modified in place.
Python
byte_array = bytearray(b'Hello')
byte_array[0] = ord('J') # Replace the first character with 'J'
print(byte_array) # Output: bytearray(b'Jello')
Common Operations
Similar to bytes, bytearrays support slicing, concatenation, membership testing, and length operations. Additionally, they have methods for modifying the content.
Key Differences Between Bytes and Bytearray
Feature |
Bytes |
Bytearray |
Mutability |
Immutable |
Mutable |
Modification |
Not allowed |
Allowed |
Use cases |
Read-only binary data |
Modifiable binary data |
Export to Sheets
Use Cases
Bytearrays are often used when you need to manipulate binary data in place, such as network communication, image processing, or data serialization.
Example:
Python
data = bytearray(b'Hello')
data[0] = ord('J') # Modify the first byte
print(data) # Output: bytearray(b'Jello')
In summary, bytearrays provide a flexible way to work with binary data when modifications are required. Understanding the difference between bytes and bytearrays is crucial for effective data handling in Python.