Skip to main content

bytearray()

The bytearray() function in Python creates a new mutable bytearray object. It can take a string, an iterable, or an integer as an argument and convert it into a byte array object, which allows for mutable modifications of bytes within the array.

Parameter Values

Parameter Description
source

Optional. A source to initialize the array. It can be an iterable, a buffer, a string, etc.

encoding

Optional. If the source is a string, this parameter specifies the encoding used to convert the string to bytes.

errors

Optional. If the source is a string, this parameter defines how encoding and decoding errors are handled.

Return Values

The bytearray() function returns a mutable array of bytes.

How to Use bytearray() in Python

Example 1:

Returns a new array of bytes which is a mutable sequence of integers in the range 0 = x 256.= x 256.

byte_array = bytearray([65, 66, 67, 68])
print(byte_array) # bytearray(b'ABCD')
Example 2:

Can also create an array of a specified size initialized with null bytes.

byte_array = bytearray(5)
print(byte_array) # bytearray(b'\x00\x00\x00\x00\x00')
Example 3:

Accepts an iterable object as an argument to initialize the bytearray.

string = 'hello'
byte_array = bytearray(string, 'utf-8')
print(byte_array) # bytearray(b'hello')