Python bytearray() Function
The Python bytearray() function returns a bytearray object. The function converts objects into bytearray objects or create empty bytearray object of specified size.
Please note that, the returned bytearray object from bytearray function can be modified, whereas the returned bytes object from bytes function is not modifiable.
Syntax
bytearray(source, encoding, errors)
Parameters
source |
Optional. Specify the source to use when creating bytearray object. Different source parameter type can be used with this function as described below:
|
encoding |
Optional. Specify encoding of the literal. |
errors |
Optional. Specify response when encoding fails. |
Example:Using bytearray() function
In the example below, bytearray() function is used to convert a string and integer into a bytearray object.
MyStr = "Hello" MyInt = 5 print(bytearray(MyStr, 'utf-8')) print(bytearray(MyInt))
The output of the above code will be:
bytearray(b'Hello') bytearray(b'\x00\x00\x00\x00\x00')
Example:Using bytearray() function with iterable
In the example below, bytearray() function is used to convert an iterable into a bytearray object.
MyList = [10, 20, 30] print(bytearray(MyList))
The output of the above code will be:
bytearray(b'\n\x14\x1e')
❮ Python Built-in Functions