You must have studied different data types in python such as strings and numeric data types like integers and floating point numbers. In this article you will learn about another data type called bytearray in python programming language. You will study the underlying concepts behind bytearray in python and will implement different types of operations on bytearray objects to understand the concepts.
What is bytearray in Python?
A bytearray in python is an array of bytes that can hold data in a machine readable format. When any data is saved in the secondary storage, it is encoded according to a certain type of encoding such as ASCII, UTF-8 and UTF-16 for strings, PNG, JPG and JPEG for images and mp3 and wav for audio files and is turned into a byte object. When we access the data again using python read file operation, it is decoded into the corresponding text, image or audio. Thus byte objects contain data that are machine readable and bytearray objects are arrays of bytes.
How to create bytearray objects in Python?
We can create a bytearray object in python using bytearray() method. The bytearray() function takes three parameters as input all of which are optional. The object which has to be converted to bytearray is passed as the first parameter. Second and third parameters are used only when the first parameter is string. In this case, the second parameter is the encoding format of the string and the third parameter is the name of the error response which is executed when the encoding fails. The bytearray() function returns a bytearray object. In the next sections, we will understand the working of bytearray() function by creating bytes objects from different data objects.
Create a bytearray object
To create a bytearray object of a given size, we can give the desired size of bytearray as input to the bytearray() function. After successful execution, it returns the bytearray object of given size initialized to zeros as follows.
myObj=bytearray(10)
print("The bytearray object is:",myObj)
print("Length of the bytearray object is:",len(myObj))
Output:
The bytearray object is: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
Length of the bytearray object is: 10
To convert a string to bytearray object, we pass the string as first input and encoding type as second input argument to the bytearray() function. It then returns the bytearray of string as follows.
myString="pythonforbeginners.com"
print("The string is:",myString)
myObj=bytearray(myString,"UTF-8")
print("The bytearray object is:",myObj)
Output:
The string is: pythonforbeginners.com
The bytearray object is: bytearray(b'pythonforbeginners.com')
We can convert a list of integers to bytearray using bytearray() function in python. The bytearray() function takes the list of integers between 0 and 255 as input and returns the corresponding bytearray object as follows.
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
Output:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
For integer values which are not between 0 to 255, the bytearray function raises ValueError as follows.
myList=[1,2,56,78,900]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 3, in <module>
myObj=bytearray(myList)
ValueError: byte must be in range(0, 256)
The List is: [1, 2, 56, 78, 900]
We can handle the above exception using python try-except as follows.
myList=[1,2,56,78,900]
print("The List is:",myList)
try:
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
except Exception as e:
print(str(e))
Output:
The List is: [1, 2, 56, 78, 900]
byte must be in range(0, 256)
Operations on bytearray objects
Although byte objects are immutable, bytearray objects are mutable and can be modified and they almost behave as python lists. Following are some common operations on bytearray objects.
Bytearray supports indexing and slicing. We can use indices to get the data at a particular index or we can slice a bytearray to get data between two indices as follows.
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
sliced_obj=myObj[0:2]
indexed_obj=myObj[1]
print("Sliced part of bytearray is:",sliced_obj)
print("Data at index 1 of bytearray is:",indexed_obj)
Output:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
Sliced part of bytearray is: bytearray(b'\x01\x02')
Data at index 1 of bytearray is: 2
As bytearray objects are mutable, we can also modify the bytearray objects using indexing and slicing as follows.
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj[0:2]=[15,16]
myObj[4]=34
print("The modified bytearray object is:",myObj)
Output:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x0f\x108N"')
We can also insert data into a bytearray object at a given index using insert() method as follows.
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj.insert(1,23)
print("The modified bytearray object is:",myObj)
Output:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x01\x17\x028NZ')
We can append data into a bytearray object using the append() method as follows.
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj.append(105)
print("The modified bytearray object is:",myObj)
Output:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x01\x028NZi')
We can also delete data at a specific index or between two indices using del statement as follows.
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
del myObj[0]
del myObj[1:3]
print("The modified bytearray object is:",myObj)
Output:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x02Z')
Conclusion
In this article, we have studied the bytearray data structure in python. We have also converted different data types to bytearray and have performed operations like appending data to a bytearray, insertion of data and deletion of data from a bytearray using built in functions.Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.