The bytearray() function in Python returns a  new array of bytes. The bytearray class is a mutable sequence of integers in 0 to 256. However, it has most of the usual methods of mutable sequences.

Python bytearray() function:


The signature for the bytearray() method is as shown below. Here, b stores an array of bytes returned by the method. It has three optional parameters.

b=bytearray(source, encoding, errors)

Parameters and return type

    1. The source is an optional parameter that takes an integer or an iterable to convert it to a byte array. Firstly, if the source is a string, it must be with an encoding parameter. However, if the source is an integer, the array will have that size and be initialized with null bytes.
    2. encoding is an optional parameter that specifies the encoding of the string if the source is a string.
    3. errors is an optional parameter that specifies the action to take if encoding conversion fails.
  • However, it returns an array of bytes.

Python Built-in Function bytearray Examples:

Example 1: We will convert an integer to an array of bytes in this example. Here, we will also take a list containing numbers and convert that into an array of bytes. As we can see, for integer parameter, byte array takes it as size and initialize with `null` value.

#Using bytearray with integers
#Using bytearray with List
n = [1, 2, 3, 4, 5]



Example 2: In this example, We will demonstrate the working of this function with the strings. However, in the absence of encoding parameter when source is string, this function will raise a TypeError exception.

#Using bytearray with string and encoding
print(bytearray('Python Programming','utf-8'))
#Using bytearray with string and without encoding
print(bytearray('Python programming'))
bytearray(b'Python Programming')
Traceback (most recent call last):
  File "", line 2, in 
    print(bytearray('Python programming'))
TypeError: string argument without an encoding

Example 3: In this case, we will create an array of bytes from byte literal. As a result, an array is created with the ASCII value of ABCD written in it.

# Creates bytearray from byte literal
a = bytearray(b"ABCD")
# iterating the value
for i in a:




The bytearray() method converts an iterable to an array of bytes. However, if the source is absent,  it creates an array of size zero.


Happy Learning 🙂