bytearray() Function in Python

Python bytearray() Function

The bytearray() function in Python is a built-in function that returns a mutable bytearray object. This function allows you to create a bytearray from different data types, such as strings, integers, or other iterable objects.

Here are some important points to note about the bytearray() function:

The syntax for the bytearray() function is as follows:

bytearray(source, encoding, errors)

Parameters:

  • source (optional): It can be an iterable object like a list or a string, or an integer specifying the desired size of the bytearray.
  • encoding (optional): It specifies the encoding to use when a string is provided as the source parameter.
  • errors (optional): It specifies how to handle encoding/decoding errors when a string is provided as the source parameter.

Return Value:

  • The bytearray() function returns a new bytearray object that can be modified. It represents a mutable sequence of bytes.

Examples:

arr = bytearray()                 # Empty bytearray
print(arr)                        # bytearray(b'')

arr = bytearray([65, 66, 67])      # Create bytearray from list of integers
print(arr)                        # bytearray(b'ABC')

arr = bytearray("Hello", 'utf-8')  # Create bytearray from string with specific encoding
print(arr)                        # bytearray(b'Hello')

arr[0] = 72                       # Modifying a byte in the bytearray
print(arr)                        # bytearray(b'Hello')

In the examples above, bytearray() is called with different arguments. The first example creates an empty bytearray. The second example creates a bytearray from a list of integers, where each integer represents the ASCII value of a character. The third example creates a bytearray from a string using the UTF-8 encoding. Finally, the fourth example modifies a byte in the bytearray by assigning a new value to its index.

The bytearray() function is commonly used when you need to work with a mutable sequence of bytes and perform operations such as modification, appending, or slicing on the byte values.