bytearray() function in Python
Introduction
The bytearray()
function returns a bytearray object which is an array of the given bytes.
The syntax of bytearray()
function is:
bytearray(source, encoding, errors)
where:
source
(optional) is used to initialize the arrayencoding
(optional) is the encoding in the case of stringserrors
(optional) is the action to take when the encoding conversion fails in the case of strings
The bytearray()
function returns a bytearray object which is a mutable sequence of integers in the range 0 <= x < 256
.
source
Parameter
The source
parameter can be used to initialize the byte array in the following ways:
Case 1: String
In the case of String, it is converted to bytes using str.encode()
. In this case, we must also provide encoding and optionally errors.
string = "I love iRead Blog."
arr1 = bytearray(string, 'utf-8')
arr2 = bytearray(string, 'utf-16')
arr3 = bytearray(string, 'utf-32')
print(arr1)
print(arr2)
print(arr3)
Output:
bytearray(b'I love iRead Blog.')
bytearray(b'\xff\xfeI\x00 \x00l\x00o\x00v\x00e\x00 \x00i\x00R\x00e\x00a\x00d\x00 \x00B\x00l\x00o\x00g\x00.\x00')
bytearray(b'\xff\xfe\x00\x00I\x00\x00\x00 \x00\x00\x00l\x00\x00\x00o\x00\x00\x00v\x00\x00\x00e\x00\x00\x00 \x00\x00\x00i\x00\x00\x00R\x00\x00\x00e\x00\x00\x00a\x00\x00\x00d\x00\x00\x00 \x00\x00\x00B\x00\x00\x00l\x00\x00\x00o\x00\x00\x00g\x00\x00\x00.\x00\x00\x00')
In the above example, we created the bytearray of a string with different string encodings.
Case 2: Integer
In this case, an array of the given size is created initialized with null values.
arr_size = 3
arr = bytearray(arr_size)
print(arr)
Output:
bytearray(b'\x00\x00\x00')
Case 3: Object
In this case, a read-only buffer of the object will be used to initialize the bytearray.
b_arr = bytearray(b"Hello World") # b_arr is a bytearray object
print(bytearray(b_arr))
Output:
bytearray(b'Hello World')
Case 4: Iterable
In this case, an array is created of the same size as that of the iterable and initialized with the elements of the iterable. However, the iterable range should be 0 <= x < 256
.
list1 = [1, 2, 3, 4]
print(bytearray(list1))
Output:
bytearray(b'\x01\x02\x03\x04')
If the list includes number(s) greater than 256, we get an error.
list2 = [8, 16, 128, 256, 512]
print(bytearray(list2))
Output:
ValueError: byte must be in range(0, 256)
Case 5: No Source
In this case, a bytearray of size 0 is created.
arr = bytearray()
print(arr)
Output:
bytearray(b'')
Conclusion
In this part, we learned about the Python bytearray()
function with the help of examples.