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:

Signature

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
print(bytearray(1)) 
print(bytearray(2)) 
print(bytearray(3))
#Using bytearray with List
n = [1, 2, 3, 4, 5]
print(bytearray(n))

Output

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

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'))
Output
bytearray(b'Python Programming')
Traceback (most recent call last):
  File "main.py", 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:
    print(i)

Output

65
66
67
68

Conclusion

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

References

Happy Learning 🙂

Leave A Comment