How to Use the Python bytearray() Function



In this article, you will learn how to use the Python bytearray() function.

Python bytearray() Function

The bytearray() function in Python creates a mutable sequence of bytes. It takes a number of arguments, depending on how you want to create the bytearray object.

Here are some common ways to use the bytearray() function:

Create an empty bytearray:
>>> b = bytearray()
>>> print(b)
Create a bytearray from a sequence of integers:
>>> b = bytearray([65, 66, 67])
>>> print(b)
Create a bytearray from a string:
>>> b = bytearray("hello", "utf-8")
>>> print(b)

Note: When creating a bytearray from a string, you must specify the encoding of the string as the second argument. In the example above, we used the “utf-8” encoding.

Create a bytearray of a specific length:
>>> b = bytearray(5)
>>> print(b)

Note: When creating a bytearray of a specific length, all bytes are initialized to 0.

Once you have created a bytearray object, you can manipulate its contents using various methods. For example, you can use indexing to get or set individual bytes:

>>> b = bytearray([65, 66, 67])
>>> b[0]
>>> b[1] = 68
>>> print(b)

You can also use slicing to get or set a range of bytes:

>>> b = bytearray([65, 66, 67])
>>> b[1:3] = bytearray([68, 69])
>>> print(b)

There are many other methods available for working with bytearray objects, such as append(), extend(), insert(), pop(), and remove(). You can find more information in the Python documentation.