Python bytearray()

Python bytearray() function returns a bytearray object that contains the array of bytes from the input source. The bytearray class is mutable, so we can change its element values.

Table of Contents

  • 2 bytearray() with no arguments
  • 3 bytearray() with string and mutability
  • 4 bytearray() with int argument
  • 5 bytearray() with iterable

Python bytearray()

Python bytearray() function syntax is:

Copy

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

source is used to initialize the bytearray objectarray elements. This is an optional argument.

encoding is optional unless source isstring. It’s used for converting the string to bytes using str.encode() function.

errors is optional parameter. It’s used if the source is string and encoding fails due to some error.

There are some specific rules followed by bytearray() function depending on the type of source.

  • If no argument is passed, empty byte array is returned.
  • If source is integer, it initializes the byte array of given length with null values.
  • If source is string, encoding is mandatory and used to convert string to byte array.
  • If source is iterable, such aslist, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Let’s look at some of the examples of bytearray() function.

bytearray() with no arguments

Copy

b = bytearray() print(b)

Output:

Copy

bytearray(b'')

bytearray() with string and mutability

Copy

# string to bytearray # encoding is mandatory, otherwise "TypeError: string argument without an encoding" b = bytearray('abc', 'UTF-8') print(b) b[1] = 65 # mutable print(b)

Output:

Copy

bytearray(b'abc') bytearray(b'aAc')

bytearray() with int argument

Copy

b = bytearray(5) print(b)

Output:

Copy

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

bytearray() with iterable

Copy

b = bytearray([1, 2, 3]) print(b)

Output:

Copy

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

That’s all for a quick guide of python bytearray() function.

You can checkout complete python script and more Python examples from our GitHub Repository .