Bytearray in Python
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))
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)
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)
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)
Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 3, in 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))
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)
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)
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)
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)
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)
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.
Related
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.
Python ByteArray: Everything you need to know!
In this article, let us learn about the ByteArray data structure in Python and learn how and when to use it in our Python programs.
For those of you in a hurry here is the short version of the answer.
ByteArray in a Nutshell
ByteArray is a data structure in Python that can be used when we wish to store a collection of bytes in an ordered manner in a contiguous area of memory.
ByteArray comes under binary data types.
You can use the bytearray() constructor to create a ByteArray object as shown below
>>> numbers = [1, 2, 3, 4] >>> myByteArray = bytearray(numbers) >>> print(myByteArray) bytearray(b'\x01\x02\x03\x04')
Here the syntax we have used is
bytearray(iterable_of_ints)
Depending on the type of data we wish to convert into an array of bytes, the ByteArray class gives us 4 different constructors are shown in the table below.
Type of Data | Constructor |
---|---|
List of integers | bytearray(iterable_of_ints) |
Strings | bytearray(string, encoding[, errors]) |
Bytes | bytearray(bytes_or_buffer) |
Empty Byte Array | bytearray() |
Empty Byte Array of a given size | bytearray(int) |
Examples of how to use each one are given further down in the article.
The table below shows the most commonly used methods in the ByteArray class
Method | Meaning |
---|---|
append() | Append a single item to the end of the bytearray |
extend() | Append all the items from the iterator or sequence to the end of the bytearray. |
insert() | Insert a given element at a specified index. |
remove() | Remove the first occurrence of a value in the bytearray. |
pop() | Remove and return a single item from B. |
clear() | Remove all items from the bytearray. |
copy() | Return a copy of the bytearray object |
count() | Return the number of non-overlapping occurrences of a given subsection in bytearray |
reverse() | Reverse the order of the values in bytearray in place. |
find() | Return the lowest index where the given subsection is found. |
Examples of how to use these above methods, along with some more useful methods are given later on in the article.
If the above answer feels insufficient do not worry as this section was meant to be a quick reference for those who are already familiar with the topic. Read on for a more complete answer where we have explained everything you need to know about ByteArrays with the help of examples!
Feel free to skip to your topic of interest using the table of contents below.