Python bytearray()

Python bytearray() creates a mutable sequence of bytes, meaning you can change its contents after it's created, unlike the immutable bytes type. It provides a way to handle raw byte data efficiently, allowing you to modify individual bytes, add or remove bytes, and perform other everyday operations when dealing with binary information.
Table of Contents

Understanding Python bytearray() Function

Python bytearray() function returns a new array of bytes, which is a mutable sequence of integers in the range 0 <= x < 256.1. Essentially, it creates a collection of bytes you can modify after making it, unlike an immutable object. You can create a bytearray object from a string (you must provide an encoding for this), an integer (it will create an array of that size, filled with null bytes), or a list of integers. This is especially helpful when dealing with binary data, such as files or network connections, where you might need to change the data on the fly.

Syntax of Python bytearray()

bytearray_object = bytearray(source, encoding, errors)

Explanation

  • bytearray_object: Variable will hold the new bytearray object that is created.
  • bytearray(): Function that creates the bytearray object.
  • source (optional): Source to initialize the array. This can be a string, integer or a list.
  • encoding (optional): If the source is a string, this specifies the encoding of the string.
  • errors (optional): If the source is a string, this specifies what to do if the encoding fails.

Example of Python bytearray()

bytearray_obj = bytearray()
print(bytearray_obj)

bytearray_obj.append(65)
print(bytearray_obj)

Explanation

  • bytearray_obj = bytearray(): Creates an empty bytearray object named bytearray_obj.
  • print(bytearray_obj): Prints the empty bytearray object, which outputs bytearray(b'').
  • bytearray_obj.append(65): Adds the integer 65 (ASCII for ‘A’) to the bytearray.
  • print(bytearray_obj): Prints the updated bytearray, which outputs bytearray(b'A').

Output

bytearray(b”)
bytearray(b’A’)


Python bytearray() with String

When you use Python bytearray() with a string as the source, you must also provide the encoding for that string. The function will then convert the string into a sequence of bytes according to the specified encoding and create a mutable byte array object from it. Standard encodings include ‘utf-8’, ‘ascii’, and ‘latin-1’. This is particularly useful when you need to manipulate text as raw bytes, for instance, when preparing data to be sent over a network or written to a binary file.

Syntax

bytearray_object = bytearray(string, encoding, errors)

Explanation

  • bytearray_object: Variable holds the bytearray object created from the string.
  • bytearray(): Function creates the bytearray object.
  • string: String you want to convert into a bytearray. It is used as input for the bytearray() function.
  • encoding: Specifies how the string should be encoded into bytes (e.g., ‘utf-8’).
  • errors: Optional parameter that specifies how encoding errors should be handled.

Example

string = "Hello"
encoding = "utf-8"
bytearray_string = bytearray(string, encoding)
print(bytearray_string)

Explanation

  • string = "Hello": Assigns the string “Hello” to the variable string.
  • encoding = "utf-8": Sets the encoding to ‘utf-8’.
  • bytearray_string = bytearray(string, encoding): Creates a bytearray from string using the specified encoding and stores it in bytearray_string.
  • print(bytearray_string): Prints the bytearray_string, which outputs bytearray(b'Hello').

Output

bytearray(b’Hello’)


Python bytearray() with Integer Argument

Using an integer as an argument for Python bytearray() creates a bytearray object of the given size, filled with null bytes (\x00). This means it initializes a mutable sequence of bytes where each byte has a value of 0, and the sequence length is equal to the integer you provided. This can be useful when you need a buffer of a specific size to work with binary data.

Syntax

bytearray_object = bytearray(integer)

Explanation

  • bytearray_object: Variable will hold the bytearray object of the specified size.
  • bytearray(): Function creates the bytearray object.
  • integer: Integer determines the size of the bytearray to be created. It is used as input for the bytearray() function.

Example

size = 5
bytearray_int = bytearray(size)
print(bytearray_int)

Explanation

  • size = 5: Assigns the integer 5 to the variable size.
  • bytearray_int = bytearray(size): Creates a bytearray of 5 null bytes and assigns it to bytearray_int.
  • print(bytearray_int): Prints bytearray_int, which outputs bytearray(b'\x00\x00\x00\x00\x00').

Output

bytearray(b’\x00\x00\x00\x00\x00′)


Python bytearray() with List

You can create a Python bytearray from a list of integers where each integer ranges from 0 to 255. Each integer in the list represents a byte value. The bytearray() function will then create a mutable sequence of bytes corresponding to the integers in the list. This is useful when you have data represented as integers and must convert it into a mutable byte format.

Syntax

bytearray_object = bytearray(list_of_integers)

Explanation

  • bytearray_object: Variable will hold the bytearray object created from the list.
  • bytearray(): Function creates the bytearray object.
  • list_of_integers: List of integers (0-255) that will be converted into a bytearray. It is used as input for the bytearray() function.

Example

my_list = [65, 66, 67, 68]
bytearray_list = bytearray(my_list)
print(bytearray_list)

Explanation

  • my_list = [65, 66, 67, 68]: Creates a list of integers named my_list.
  • bytearray_list = bytearray(my_list): Creates a bytearray from my_list and assigns it to bytearray_list.
  • print(bytearray_list): Prints bytearray_list, which outputs bytearray(b'ABCD') (65-68 are ASCII values for ABCD).

Output

bytearray(b’ABCD’)


Conclusion

Python bytearray() is a handy function for creating and manipulating mutable sequences of bytes in Python. Whether you’re working with strings, integers, or lists of integers, bytearray() provides a way to convert these data types into a byte format that can be modified. Understanding how Python bytearray works with different data types is essential for tasks that involve binary data manipulation, such as file I/O, network programming, and cryptography. You can always get a mutable sequence of bytes using bytearray() function.


Also Read

Python bool()

Python callable()


Python Reference

python bytearray()

Table of Contents