The bytearray() function in Python creates a bytearray object which is an array of bytes.
It’s mutable (can be modified), unlike bytes object which is immutable.
Remember that each element in a bytearray is an integer in the range 0 <= x < 256.
Syntax
bytearray(source, encoding, error)
Parameters
- source (Optional) – Initializes the array of bytes. The source can be a string, an integer, or an iterable of integers.
- encoding (Optional) – If the source is a string, the encoding is the name of the encoding used to encode the string.
- errors (Optional) – Specifies the action to take when encoding encounters errors.
Return value
It returns the a new array of bytes.
Example 1: String with encoding
new_str = 'Hello CR7'
byte_array = bytearray(new_str, 'utf-8')
print(byte_array)
Output
bytearray(b'Hello CR7')
Once you have a bytearray, you can modify it:
# Replace 'CR7' with 'M10'
byte_array[-3:] = b'M10'
print(byte_array)
Output
bytearray(b'Hello M10')
Example 2: Passing an integer as an argument
It creates a bytearray of that size filled with null bytes.
size = 6
byte_array = bytearray(size)
print(byte_array)
Output
bytearray(b'\x00\x00\x00\x00\x00\x00')
Example 3: Using with List
num_list = [5, 3, 1, 7]
byte_array = bytearray(num_list)
print(byte_array)
Output
bytearray(b'\x05\x03\x01\x07')
Example 4: No arguments
This creates an empty bytearray.
empty_byte_array = bytearray()
print(empty_byte_array)
Output
bytearray(b'')
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.