Python Tutorial Python Advanced Python References Python Libraries

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:
  • String : Converts the string into bytearray object. encoding parameter must be provided.
  • Integer : Creates an bytearray object of specified size.
  • Object : Creates a bytearray object using read-only buffer of the object.
  • Iterable : Creates a bytearray object of size equal to the iterable count and initialized to the iterable elements. Iterable must contain elements between 0 <= i < 256.
  • No source : Creates a bytearray object of size 0.
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