Python bytearray()

The bytearray() method returns a bytearray object which is an array of the given bytes.

The syntax of bytearray() method is:

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

The bytearray() method returns a bytearray object which is a mutable (can be modified) sequence of integers in the range 0 <=x < 256.

If you want the immutable version, use bytes() method.


bytearray() Parameters

The bytearray() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if source is a string, the encoding of the string.
  • errors (Optional) - if source is a string, the action to take when the encoding conversion fails (Read more: String encoding)

The source parameter can be used to initialize the byte array in the following ways:

Different source parameters
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.

Return value from bytearray()

The bytearray() method returns an array of bytes of the given size and initialization values.


Example 1: Array of bytes from a string

string = "Python is interesting."

# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

When you run the program, the output will be:

bytearray(b'Python is interesting.')

Example 2: Array of bytes of given integer size

size = 5

arr = bytearray(size)
print(arr)

When you run the program, the output will be:

bytearray(b'\x00\x00\x00\x00\x00')

Example 3: Array of bytes from an iterable list

rList = [1, 2, 3, 4, 5]

arr = bytearray(rList)
print(arr)

When you run the program, the output will be:

bytearray(b'\x01\x02\x03\x04\x05')