The bytearray class in Python

Overview:

The bytearray class in Python abstracts a sequence that holds a set of byte values. The bytearray is a mutable sequence. 

The minimum value an element can assume in a bytearray is 0 and the maximum value is 255. In short it can hold ASCII range and the remaining 128 values.  The difference between a bytes and a bytearray is that, a bytearray is a mutable sequence and a bytes is an immutable sequence.

Removal and replacement of an element or a slice is supported by the bytearray. The bytearray also supports extending it using its own elements or with the elements of another bytearray. A bytearray can be created using the constructor or using the fromhex() method. A bytearray is suitable to hold large number of integers in the range of 0-255. 

Example: Default bytearray creation

# Example Python program that creates 
# - An empty bytearray
# - A bytearray of length 'n' initialized with zeros

# Create an empty bytearray
emptyBA = bytearray() 
print("Empty bytearray:")
print(emptyBA)

print("Length of an empty bytearray:")
print(len(emptyBA))

# Create an array of defined length 
# The bytes are zero filled by default.
seqLength = len("Hello World")
ba = bytearray(seqLength)  

print("A bytearray right after its creation:")
print(ba)

print("Length of the bytearray:")
print(len(ba))

# Replace the bytearray 
ba = b"Hello World"
print("The bytearray after replacing its contents:")
print(ba)

Output:

Empty bytearray:
bytearray(b'')
Length of an empty bytearray:
0
A bytearray right after its creation:
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
Length of the bytearray:
11
The bytearray after replacing its contents:
b'Hello World'

Example - Create bytearrays from text strings using different encodings:

# Example Python program that creates bytearrays 
# from text strings using different encodings

# Created using ASCII encoding
gmEnglish = "Good morning!"
asciiBytes = bytearray(gmEnglish, "ASCII") 
print("Original string(in English):")
print(gmEnglish)
print("Byte array:")
print(asciiBytes)

# Created using UTF-16 encoding
gmTamil = "காலை வணக்கம்"
fromUTF16 = bytearray(gmTamil, "UTF-16") 
print("Original string(in Tamil):")
print(gmTamil)
print("Byte array:")
print(fromUTF16)

# Created using UTF-32 encoding

gmHebrew = "בּוֹקֶר טוֹב"
fromUTF32 = bytearray(gmHebrew, "UTF-32") 
print("Original string(in Hebrew):")
print(gmHebrew)
print("Byte array:")
print(fromUTF32)

Output:

Original string(in English):
Good morning!
Byte array:
bytearray(b'Good morning!')
Original string(in Tamil):
காலை வணக்கம்
Byte array:
bytearray(b'\xff\xfe\x95\x0b\xbe\x0b\xb2\x0b\xc8\x0b \x00\xb5\x0b\xa3\x0b\x95\x0b\xcd\x0b\x95\x0b\xae\x0b\xcd\x0b')
Original string(in Hebrew):
בּוֹקֶר טוֹב
Byte array:
bytearray(b'\xff\xfe\x00\x00\xd1\x05\x00\x00\xbc\x05\x00\x00\xd5

\x05\x00\x00\xb9\x05\x00\x00\xe7\x05\x00\x00\xb6\x05\x00\x00\xe8

\x05\x00\x00 \x00\x00\x00\xd8\x05\x00\x00\xd5\x05\x00\x00\xb9\x05

\x00\x00\xd1\x05\x00\x00')

The UTF-16 and UTF-32 formats begin with the Byte Order Mark. In this example, the resultant bytearrays start with \xff\xfe which indicates that the data is in little endian format. For big endian format the Byte Order Mark will be \xfe\xff.

Example - Create bytearray from a string of hexadecimal values:

# Example Python program that creates a 
# bytearray from a string of hexdecimal 
# values
hexString = "041042043044"
ba = bytearray.fromhex(hexString)
print("Hexadecimal string:")
print(hexString)
print("The bytearray created from a string of hexadecimal values:")
print(ba)

# Try creating a bytearray with three hexadecimal
# values
hexString = "045046047"
print("Creating a bytearray with three hex values:")
print(hexString)
ba = bytearray.fromhex(hexString)
print(ba)

 Output:

Hexadecimal string:
041042043044
The bytearray created from a string of hexadecimal values:
bytearray(b'\x04\x10B\x040D')
Creating a bytearray with three hex values:
045046047
Traceback (most recent call last):
  File "/Users/vinodh/PythonProgs/ba_from_hex.py", line 16, in <module>
    ba = bytearray.fromhex(hexString)
ValueError: non-hexadecimal number found in fromhex() arg at position 9

Creating a bytearray from a hexadecimal string requires the string to contain even number of hexadecimal values. Passing an odd number of hexadecimal values to the fromhex() method will result in an error stating that “non-hexadecimal number found in fromhex() arg” for the reason being a byte can store two hexadecimal values – each four bits of a byte stores one hexadecimal number each.

 


Copyright 2026 © pythontic.com