What is bytearray in Python: Explanation and Examples
bytearray in Python is a mutable sequence of bytes, meaning you can change its contents after creation. It is useful for handling binary data like files or network messages where you need to modify bytes directly.How It Works
Think of bytearray as a list of small boxes, each holding a number from 0 to 255. These numbers represent bytes, the basic units of data in computers. Unlike strings, which are fixed and cannot be changed, a bytearray lets you open these boxes and change the numbers inside.
This makes bytearray very handy when you work with raw data like images, sounds, or network packets, where you might need to tweak the bytes directly. You can create a bytearray from a string, a list of numbers, or even another bytes-like object, and then modify it as needed.
Example
This example shows how to create a bytearray, change one byte, and print the result.
data = bytearray(b'hello') data[0] = 72 # Change 'h' (104) to 'H' (72) print(data) print(data.decode())
When to Use
Use bytearray when you need to work with binary data that can change. For example:
- Modifying file contents before saving.
- Building or editing network messages byte by byte.
- Working with image or audio data where you adjust bytes directly.
It is also useful when performance matters, as modifying a bytearray is faster than creating new bytes objects repeatedly.
Key Points
- Mutable: You can change the bytes inside a
bytearray. - Bytes range: Each element is a number from 0 to 255.
- Created from: Strings, lists of integers, or bytes.
- Useful for: Binary data manipulation.
Key Takeaways
bytearray is a mutable sequence of bytes useful for binary data.bytearray is efficient for performance.