Python bytearray Function

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

The first thing that comes to mind when we hear about the bytearray is that array of bytes. We are talking about a particular function in Python that returns the array of bytes. As we are familiar, that Python supports a wide range of types to store sequences. In total, there are six types, and one of them is the bytearray. In this article, we will be discussing about the bytearray function in Python.

Python Bytearray Function

Python has an inbuilt function named bytearray(). The bytearray function in Python returns a bytearray object. This bytearray object is a simple array of bytes. Basically, the array is a sequence of integers where each integer lies in a range of 0 to 255. One more thing to be noted is that the generated sequence of integers is mutable. The property of the mutable sequence is that its state and contents can be changed after the creation of the sequence.

Syntax of Bytearray Function

The syntax of the bytearray function is as follows:

or

Here, all three parameters are optional. The details about each parameter will be discussed in the following section.

Parameters of Python Bytearray Function

Considering the above-discussed syntax, we will be discussing about all three parameters of the bytearray function in detail.

Source

The first optional parameter is the source. This parameter can be used to initialize the array in various ways.

  • If the source parameter is a string, you must additionally specify the encoding and, if desired, the errors argument. The bytearray() then uses str.encode() to convert the string to bytes.
  • If the source parameter is an integer value say 'n', then an array will be created of null bytes and the size of the array will be 'n'.
  • If an object complies with the buffer interface; the object's read-only buffer will be utilized to initialize the bytes array.
  • If the source parameter is iterable, then it must be iterable of integers that are used as the array's initial contents and lies between the range of 0 to 255.
  • If we pass zero arguments, then an array of size zero will be returned by the bytearray() function.

Encoding and Error

  • Encoding is the second optional parameter of the Python bytearray function. It represents the encoding of the string if the source parameter is the string. Encoding can be done in various ways like utf-8, utf-16, etc.
  • Error is the third optional parameter of the Python bytearray function. It represents the action that needs to be taken if the encoding of the source parameter fails. Following are some of the error arguments:
    • ‘strict’: it raises an exception.
    • ‘replace’: it replaces malformed data with a suitable replacement marker.
    • ‘ignore’: it ignores malformed data and continues.
    • ‘xmlcharrefreplace’: it replaces with the appropriate XML character reference (used for encoding only).
    • ‘backslashreplace’: it replaces with backslashed escape sequences (used encoding only).

Return Value of Python Bytearray Function

The Python bytearray function returns the array of bytes. Let us understand this by an example.

Code

Output

Explanation

In the above example, we have called the bytearray function three times. Every time we pass an integer value to the function. As we have discussed earlier, if an integer is passed as an argument to the bytearray function, then it returns the array having the size of the integer. The default value of the bytearray is set to null. In the first line of the output, the array is of size five. In the second and third lines, the size of the array is seven and three, respectively. If we do not pass any parameter to the bytearray function then it will return bytearray of size zero. We can see this in the fourth line of the code.

Exceptions of Python Bytearray Function

While using the python bytearray function, there is one exception that you need to take care of. Suppose the source parameter that you provide to the bytearray function is a string. Then you need to provide its encoding type else the TypeError exception will be returned. Let us understand this by the following example.

Code

Output

Explanation In the above example, we are trying to convert a string "Welcome to Scaler!" to a bytearray without providing any encoding type. We are getting a TypeError as it is mandatory to provide encoding type to the bytearray function when the source parameter is a string.

Python Bytearray Function Examples

In this section, we will be dealing with the different types of examples based on the Python bytearray function.

An Array of Bytes from A String

In this example, we will be converting a string into an array of bites. As this is the case of a string to bytearray, then we have to provide a second optional parameter, i.e., the encoding type of a string.

Code

Output

Explanation

In the above example, we have converter a string into a bytearray. The arr1 is formed by converting a string to bytearray using utf-8 encoding, and arr2 is formed using utf-16 encoding.

Example with Error Argument

In this example, we will be dealing with the an error that may occur while encoding a string.

Code

Output

Explanation In the above example, we can see that the string contains a character () that cannot be encoded using ascii encoding. So we are using 'ignore' as the third parameter in the bytearray function. This will handle the error that occurs during encoding, and also will ignore malform data.

An Array of Bytes of Given Integer Size

In this example, we will be passing an integer as the first optional parameter to the Python bytearray function. This will be resulting a bytearray that will have null as the default value. The size of the bytearray will be the integer provided as a parameter.

Care has to be taken while passing an integer as an argument through the bytearray() function. There is no specific upperlimit for the integer argument. But the theoretical limit is 2^32 (4 GB) for 32-bit OS and 2^64 for 64-bit OS. But the actual limit will be the amount of virtual memory available for the process.

Code

Output

Explanation

In the above example, we have passed an integer as the first optional parameter. After executing a bytearray function, the bytearray of size 10 is formed. Every value inside the bytearray is set to null by default.

An Array of Bytes From an Iterable List

In this example, we will be converting an iterable list to a bytearray. We will be passing an iterable list in the python bytearray function as the first optional parameter. Also, we need to take care that every integer from the iterable list must lie in the range of 0 to 255. If any integer from the iterable crosses the range then the python bytearray function will give ValueError.

Code

Output

Explanation In the above example, we have passed an iterable list as the first optional argument in the Python bytearray function. The bytearray function will convert the iterable list to a bytearray.

Conclusion

  • The python bytearray function returns a bytearray object. It is also capable of creating empty bytearray.
  • The python bytearray function can accept three optional arguments. The first argument is "source", the second argument is "encoding", and the third argument is "error".
  • When we pass the first optional argument as a string to the bytearray function, we must specify its encoding type. Or else it will give a TypeError.
  • If we don't pass any argument to the bytearray function, then it will return a bytearray of size zero.

FAQs

Q: What is the Bytearray Function in Python?

A: A bytearray object is the result of the bytearray() function. It can create empty bytearray objects of the desired size or transform items into bytearray objects.

Q: Why is Bytearray Used?

A: Bytearray is faster since it doesn't have to consider different element types. It is possible to save game data online, encrypt data, compress data, and transform a BitmapData object into a PNG or JPG file with the help of the highly powerful Class known as ByteArray.

Q: What is the Difference Between Bytes and Bytearray?

A: Bytes() and bytearray() return different types of objects: bytes() returns an immutable object, whereas bytearray() returns a mutable object.

Q: Are Bytearrays Immutable?

A: No, bytearrays are mutable. A modifiable series of integers in the range of 0 to 255 makes up the bytearray type. It has the majority of the commonly used mutable sequence methods listed in Mutable Sequence Types, as well as the majority of the methods listed under the bytes type in Bytes and Byte Array Methods.

Read More: