Python bytearray() With Examples

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.

Python bytearray()

Python bytearray() function syntax is:


class bytearray(]])

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

encoding is optional unless source is string. 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 as list, 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


b = bytearray()
print(b)

Output:


bytearray(b'')

bytearray() with string and mutability


# 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:


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

bytearray() with int argument


b = bytearray(5)
print(b)

Output:


bytearray(b'x00x00x00x00x00')

bytearray() with iterable


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

Output:


bytearray(b'x01x02x03')

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.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: