Python bytearray() Method

The bytearray() method returns a bytearray object, which is an array of the given bytes. The bytearray class is a mutable sequence of integers in the range of 0 to 256.

Syntax:

bytearray(source, encoding, errors)

Parameters:

  1. source: (Optional) An integer or iterable to convert it to a byte array.
    1. If the source is a string, it must be with the encoding parameter.
    2. If the source is an integer, the array will have that size and will be initialized with null bytes.
    3. If the source is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
    4. If the source is the iterable object, it must have integer elements only in the range 0 to 256.
  2. encoding: (Optional) The encoding of the string if the source is a string.
  3. errors: (Optional) The action to take if the encoding conversion fails.

Return Value:

Returns an array of bytes.

The following example converts integer to bytearrays.

Example: bytearray()
print(bytearray(1)) # A byte array of size 1
print(bytearray(2)) # A byte array of size 2
print(bytearray(3)) # A byte array of size 3
Output
bytearray(b'\x00')
bytearray(b'\x00\x00')
bytearray(b'\x00\x00\x00')

If the source argument is a string and no encoding method is specified, a TypeError exception is returned.

Example:
print(bytearray('Hello World'))
Output
TypeError: string argument without an encoding

The encoding method needs to be specified to return a bytearray object of the string, as shown below.

Example: String to Bytearray
print(bytearray('Hello World','utf-8'))
Output
bytearray(b'Hello World')

An iterable can also be converted to a bytearray object, as shown below.

Example: Iterable to Bytearray
nums = [1, 2, 3, 4, 5]
print(bytearray(nums))
Output
bytearray(b'\x01\x02\x03\x04\x05')