bytearray() Built-in Function


Python - bytearray()

Python bytearray() builtin function is used to create a mutable sequence of bytes. Each element of the bytearray object can be in the range of 0 <= x < 256.

In this tutorial, you will learn the syntax of bytearray() function, and then its usage with the help of example programs.

Syntax

The syntax of bytearray() function is

bytearray(source, encoding, errors)

where

ParameterDescription
sourceThe source for creating bytearray object.
If source is an integer, then bytearray() returns a byte array of this size.
If source is string, then bytearray() returns byte array created using the characters in the string, and specified encoding.
encodingThe encoding to be used, if source is a string.
errorsThe action to be performed if encoding fails.

Note: Since bytearray object is mutable, individual bytes of the bytearray object can be modified.

Examples

1. Create bytearray object of size 10

In the following program, we create a bytearay object of size 10. The initial value of each byte would be 0, in hexadecimal that would be \x00.

Python Program

x = bytearray(8)
print(x)

Output

bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')

2. Create bytearray from a string

In the following program, we pass a string value to bytearray() function, to create bytearray object from the given string. We specify the encoding 'utf-8' as second argument.

Python Program

x = bytearray('hello world', 'utf-8')
print(x)

Output

bytearray(b'hello world')

3. Modify bytearray

We can modify the elements of the bytearray, which are bytes. You may assign new values to the elements of bytearray referenced by the index.

Python Program

x = bytearray('hello world', 'utf-8')
x[2] = 77
x[3] = 78
x[4] = 79
print(x)

Output

bytearray(b'heMNO world')

Summary

In this tutorial of Python Examples, we learned the syntax of bytearray() function, and how to create a bytearray object of specific size, or a bytearray object initialised using string argument, with examples.