bytearray(source=b'')

class bytearray(source, encoding)

class bytearray(source, encoding, errors)

The bytearray() function returns a bytearray object, which is an array of specified bytes.

Parameters

The bytearray() function accepts three optional parameters:

  • source (Optional) — source to initialize the byte array.
  • encoding (Optional) — if the source is a string, the encoding of the string.
  • errors (Optional) — if the source is a string, action to take when encoding conversion fails.

Return Value

Returns a byte array. The bytearray type is a mutable sequence of integers in the range 0 ≤ X < 256. The source parameter can be used for initial array initialization:

  • If source is a string, you must also provide encoding and optionally errors.
  • If source is an integer, the array will have the size source and be initialized with bytes of value 0.
  • If source is an object, it must support the buffer interface. A buffer intended for reading will be used to initialize the byte array.
  • If source is an iterable, its elements must be integers in the range 0 ≤ X < 256. The array will be initialized with these numbers.
  • If source is not provided, it returns an empty bytearray.

Examples

bytearray('Hello, Python!', 'utf-8')  
# bytearray(b'Hello, Python!')
bytearray(5)
# bytearray(b'\x00\x00\x00\x00\x00')
bytearray([1, 2, 3])
# bytearray(b'\x01\x02\x03')