Python bytearray()
Function
The bytearray() function in Python is used to create a mutable sequence of bytes. It’s like a list, but each item is a byte (0 to 255). This is useful when you want to manipulate binary data such as files, images, or streams.
Syntax
bytearray([source[, encoding[, errors]]])
Parameters:
source
(optional) – can be a string, bytes, iterable of integers, or an integer size.encoding
(optional) – required if the source is a string.errors
(optional) – how to handle encoding errors ('strict', 'ignore', etc.).
Returns:
- A new bytearray object (mutable bytes).
Example 1: Create an Empty Bytearray
b = bytearray()
print(b)
bytearray(b'')
Example 2: From a List of Integers
b = bytearray([65, 66, 67])
print(b)
bytearray(b'ABC')
Example 3: From a String with Encoding
b = bytearray("hello", "utf-8")
print(b)
bytearray(b'hello')
Example 4: Modify Bytearray
b = bytearray("hello", "utf-8")
b[0] = 72 # Replace 'h' with 'H'
print(b)
bytearray(b'Hello')
Use Cases of bytearray()
- Modify byte-level data (e.g., in file I/O or network sockets)
- Efficiently handle binary data (images, audio, etc.)
- Useful for encryption, hashing, and compression tasks
Common Mistakes
- Forgetting encoding: When creating from a string, always specify encoding.
- Invalid integers: Values in iterable must be between 0 and 255.
Interview Tip
In low-level system or network programming, you may be asked to handle binary protocols. Knowing bytearray()
is essential when you need mutable binary structures.
Summary
bytearray()
creates a mutable array of bytes.- Supports multiple input types: string, list, bytes, or integer.
- Commonly used for working with binary files and buffers.
Practice Problem
Write a program that converts a user-entered string into a bytearray, modifies the first character, and prints the result.
text = input("Enter a word: ")
b = bytearray(text, "utf-8")
b[0] = b[0] - 32 # Make first character uppercase
print("Modified:", b)