Python bytearray() Function

The bytearray() function in Python creates a bytearray object which is an array of bytes.

It’s mutable (can be modified), unlike bytes object which is immutable.

Remember that each element in a bytearray is an integer in the range 0 <= x < 256.

bytearray() Function on String

Syntax

bytearray(source, encoding, error)

Parameters

  1. source (Optional) Initializes the array of bytes. The source can be a string, an integer, or an iterable of integers.
  2. encoding (Optional) – If the source is a string, the encoding is the name of the encoding used to encode the string.
  3. errors (Optional)Specifies the action to take when encoding encounters errors.

Return value

It returns the a new array of bytes.

Example 1: String with encoding

new_str = 'Hello CR7'

byte_array = bytearray(new_str, 'utf-8')

print(byte_array)

Output

bytearray(b'Hello CR7')

Once you have a bytearray, you can modify it:

# Replace 'CR7' with 'M10'
byte_array[-3:] = b'M10'

print(byte_array)

Output

bytearray(b'Hello M10')

Example 2: Passing an integer as an argument

It creates a bytearray of that size filled with null bytes.

Passing an integer as an argument

size = 6

byte_array = bytearray(size)

print(byte_array)

Output

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

Example 3: Using with List

Using with List

num_list = [5, 3, 1, 7]

byte_array = bytearray(num_list)

print(byte_array)

Output

bytearray(b'\x05\x03\x01\x07')

Example 4: No arguments

This creates an empty bytearray.

empty_byte_array = bytearray()

print(empty_byte_array)

Output

bytearray(b'')

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.