The bytearray() Function returns a bytearray object, which is a mutable sequence of integers in the range 0 <=x < 256. If you want immutable sequence of integers, use bytes() function.
Syntax of bytearray() Function
bytearray(source, encoding, error)
bytearray() Parameters
As mentioned in the syntax of bytearray() function, this method can take upto three parameters. All these three parameters are optional, when no parameter is passed to bytearray(), it returns the array of size 0.
source (Optional) – It initializes the array of bytes. If the source is an integer, an empty bytearray object of the specified size is created and if the source is a String, make sure that you specify the encoding of the source.
encoding (Optional) – You must also provide encoding if the source is a string.
errors (Optional) – Actions that needs to be taken when the encoding of string fails.
Return value from bytearray() function
The bytearray() method returns an array of bytes of the given size.
Example 1: Array of bytes from an integer
When an integer is passed as an argument to the bytearray(), it creates the array of that size and initialize the array with null bytes. In the following example, we are passing the value 4 to the bytearray() function so it created the array of size 4 and initialized the elements with null bytes.
num = 4 arr = bytearray(num) print(arr)
Output:
bytearray(b'\x00\x00\x00\x00')
Example 2: bytearray() when the parameter is a String
When a String is passed to the bytearray() function, we must also provide the encoding. In the following example we are passing the same String to the function but with different encoding and as you can see we get a different output for each encoding.
str = "Hello" # providing the encoding along with String arr1 = bytearray(str, 'utf-8') arr2 = bytearray(str, 'utf-16') print(arr1) print(arr2)
Output:
Example 3: Array of bytes from a list
In the following example we are passing a list to the bytearray() and it returns the mutable sequence of bytes.
lis = [1, 2, 3, 4, 5, 6] arr = bytearray(lis) print(arr)
Output:
bytearray(b'\x01\x02\x03\x04\x05\x06')
Example 4: When no parameter is passed to the bytearray()
If no parameter is passed to the bytearray() method, it creates an array of size 0.
arr = bytearray() print(arr)
Output:
bytearray(b'')
References:
1. bytearray() docs
2. Where are Python bytearray() is used?
Leave a Reply