Python bytearray() Function

The bytearray() function in Python returns a bytearray object or converts any object into a bytearray object. For example:

x = bytearray()
print(type(x))

print(bytearray(5))

a = "codescracker"
x = bytearray(a, "utf-8")
print(x)

b = "python"
b = bytearray(b, "utf-16")
print(b)

The snapshot given below shows the sample output produced by above Python program, demonstrating the bytearray() function:

python bytearray function

Note: Unlike bytes(), bytearray() returns an object that can be modified.

Python bytearray() Function Syntax

The syntax of bytearray() function is:

bytearray(x, encoding, error)

where x refers to the source. If the source is an integer type, then an empty bytearray object with specified size, with given x integer value, will get created. The encoding is needed when x is of string type. The error is used when the encoding fails or mismatched. All the three parameters are optional.

Note: We can use string, integer, iterable, or object type as value of x.

Python bytearray() Function Example

Here is a simple example of bytearray() function in Python:

mylist = [3, 6, 8, 2]
ba = bytearray(mylist)
print(ba)

mystr = "codes cracker dot com"
ba = bytearray(mystr, "utf-8")
print(ba)

mysize = 10
ba = bytearray(mysize)
print(ba)

The sample output of this program, is shown in the snapshot given below:

python bytearray function example

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!