The python bytearray function is used to return a bytearray object. It can either convert objects to bytearray objects or construct an empty bytearray object of the desired size.
Syntax:
bytearray([source[, encoding[, errors]]])
bytearray() Parameters
bytearray() takes three optional parameters:
- source (Optional) – source initializes the array of bytes
Depending on the type of source, the bytearray() function follows some specific rules.
- If there is no parameter, an empty byte array is returned.
- If the source is a string, the encoding argument must be used.
- The array will have the same size as the source and will be initialized with null bytes if the source is an integer.
- If the source is a buffer interface object, the bytes array will be initialized with a read-only buffer from the object.
- If the source is an iterable object, the elements must all be integers in the range 0 to 256.
- encoding (Optional) – If the source is a string, the string’s encoding is returned.
- errors (Optional) – if the source is a string when encoding fails, it takes action.
Return value from bytearray()
The bytearray() function returns a byte array with the specified size and initialization settings.
Example 1: Array of bytes from a string
string = "Python is my favorite subject."
# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)
Output:
bytearray(b'Python is my favorite subject.')
Example 2: Array of bytes of given integer size
size = 5
arr = bytearray(size)
print(arr)
Output:
bytearray(b'\x00\x00\x00\x00\x00')
Example 3: Array of bytes from an iterable list
rList = [1, 2, 3, 4, 5]
arr = bytearray(rList)
print(arr)
Output:
bytearray(b'\x01\x02\x03\x04\x05')
What is a Bytearray in Python?
The bytearray() method returns a bytearray object, which is an array of bytes. It returns a mutable series of integers between 0 and 256. The source parameter of the ByteArray is used to initialize the array. Such as:
Method 1:
Bytearray() transforms a string to bytes using str.encode() if the encoding and errors parameters are given
Source Code:
str = "Geeksforgeeks"
 Â
# Using Unicode 8 and 16 toÂ
# encode the string
array1 = bytearray(str, 'utf-8')
array2 = bytearray(str, 'utf-16')
 Â
print(array1)
print(array2)
Output:
bytearray(b'Geeksforgeeks')
bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00')
Method 2:
If the value is an integer, it produces an array of that size with null bytes.
Source Code:
size = 3
 Â
# will make an array of the #specified size and fill it with nullÂ
# bytes
array1 = bytearray(size)
 Â
print(array1)
Output:
bytearray(b'\x00\x00\x00')
Method 3:
The read-only buffer will be utilized to initialize the bytes array if it is an Object.
Source Code
# Bytearray is created from a byte literal
arr1 = bytearray(b"abcd")
 Â
#the value being iterated
for value in arr1:
    print(value)
     Â
# Create a bytearray object
arr2 = bytearray(b"aaaacccc")
 Â
# count bytes from the buffer
print("Count of c is:", arr2.count(b"c"))
Output:
97
98
99
100
Count of c is: 4
Â
Method 4:Â
If an Iterable(range 0=x 256) is used as the array’s initial contents
Source Code
# simple list of integers
list = [1, 2, 3, 4]
 Â
# iterable as source
array = bytearray(list)
 Â
print(array)
print("Count of bytes:", len(array))
Output:
bytearray(b'\x01\x02\x03\x04')
Count of bytes: 4
Method 5:
If there is no source, a zero-sized array is constructed.
Source Code
# There will be a size 0 array formed.
 Â
# iterable as source
array = bytearray()
 Â
print(array)
Output:
bytearray(b'')
What is the Difference Between Bytes and bytearray in Python?
The bytes and bytearray classes both feature arrays of bytes with values ranging from 0 to 255 for each byte. The main difference is that a bytes object is immutable, which means that once formed, its elements cannot be changed. A bytearray object, on the other hand, allows you to change its elements.
Program to append bytes and bytearrays
The ‘+ operator’ can be used to catenate bytes and bytearray objects. Note that the catenated result inherits the first argument’s type, so a+b produces bytes object, while b+a produces a bytearray.
Source Code
>>> a = bytes(3)
>>> a
b'\x00\x00\x00'
>>> b = bytearray(4)
>>> b
bytearray(b'\x00\x00\x00\x00')
>>> a+b
b'\x00\x00\x00\x00\x00\x00\x00'
>>> b+a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00')
What is a Bytearray?
A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.
Example to convert integer to bytearrays
>>> a = bytes(3)
>>> a
b'\x00\x00\x00'
>>> b = bytearray(4)
>>> b
bytearray(b'\x00\x00\x00\x00')
>>> a+b
b'\x00\x00\x00\x00\x00\x00\x00'
>>> b+a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00')
Is Bytearray mutable in python?
Yes, the Bytearray function in Python is mutable. This indicates that the elements of the function can be easily altered.Â
For example:
b = bytearray('abc', 'UTF-8')Â
print(b)Â
b[1] = 65 # mutableÂ
print(b)
Output:
bytearray(b'abc')
bytearray(b'aAc')
Leave a Reply