Python – Find Byte Array Object – bytearray() Function with Examples

bytearray() function is used to find the bytearray object in Python for the given inputs. The bytearray object is the mutable sequence of integers in the range of 0 <=x < 256. Where mutable sequence means the sequence that can be change. For finding Immutable Bytes Object use bytes() function.
bytearray() function is a part of Python Built-in Functions (check list)

Syntax of bytearray() Function

The syntax of bytearray() function in Python is:

bytearray([source[, encoding[, errors]]])


Parameters of bytearray() Function in Python

source – Where source is the source who initialize the array of bytes.
encoding – Where encoding is the encoding of the string if the source is a string.
errors – Where errors is the action we want to perform when string encoding will fail. We use errors if source is a string.All three parameters are optional.We can use string, integer and objects etc as a source of bytearray().

Type Description
String Converts the string to bytes using str.encode() Must also provide encoding and optionally errors
Integer Creates an array of provided size, all initialized to null
Object Read-only buffer of the object will be used to initialize the byte array
Iterable Creates an array of size equal to the iterable count and initialized to the iterable elements Must be iterable of integers between 0 <= x < 256
No source (arguments) Creates an array of size 0.



bytearray() function is available and compatible with both Python 2.x and 3.x.


Return Value of bytearray() Function in Python

bytearray() function returns a bytearray object which is a mutable sequence of integers(that can be change) in the range of 0 <=x < 256 for the given inputs.For returning an immutable sequence use the bytes() function of Python built-in Library.


Python bytearray() Function Example 1

Find array of bytes from a string.

stringValue = "This is my Test String."

# string value passed to bytearray with utf-8 encoding parameter
myArray = bytearray(stringValue, 'utf-8')

bytearray(b'This is my Test String.')


Python bytearray() Function Example 2

Find array of bytes of given integer size.

integerValue = 7

myArray = bytearray(integerValue)



Python bytearray() Function Example 3

Find array of bytes from an iterable list.

elementList = [5,6,7,8]

myArray = bytearray(elementList)