Python bytearray() Function: A Practical Guide

When I build small file-processing tools or work with API payloads, I often need to change binary data before saving or sending it. A regular Python string will not help because strings store text and do not allow changes in place. Even bytes objects stay fixed after creation.

That is where the Python bytearray() function becomes useful. It gives you a mutable sequence of byte values, so you can update individual bytes, append data, slice content, and write binary output without rebuilding the entire value each time.

In this guide, you will learn how to create, modify, convert, and use bytearray() in practical Python scripts.

What Is the Python bytearray() Function?

The Python bytearray() function creates a mutable sequence of bytes. A byte is a whole number from 0 through 255. Computers use bytes to represent raw binary information such as file content, images, audio, network packets, encrypted values, and encoded text.

The syntax is:

bytearray([source[, encoding[, errors]]])

The source argument can be:

  • An integer that creates an empty byte array of that size
  • A string plus an encoding such as UTF-8
  • A list or tuple containing integers from 0 through 255
  • A bytes object
  • Another bytearray object
  • Any iterable that returns valid byte values

Unlike bytes, a bytearray lets you change data after creating it.

Here is a quick example:

customer_name = "Emma Johnson"

customer_bytes = bytearray(customer_name, "utf-8")

print(customer_bytes)
print(type(customer_bytes))

Output:

bytearray(b'Emma Johnson')
<class 'bytearray'>

I executed the above example code and added the screenshot below.

Python bytearray() Function

The output starts with bytearray(b'...'), which tells you that Python stored the text as bytes. UTF-8 is an encoding, meaning a rule Python uses to convert readable characters into binary byte values.

If you need a refresher on text-to-binary conversion, see how to convert a string to bytes in Python.

Pro Tip: I use bytearray when my script must edit binary content several times. If I only need to read or pass binary data unchanged, I usually choose bytes because it clearly communicates that the value should remain fixed.

Python bytearray() vs bytes

Both bytearray and bytes hold binary data. The key difference is mutability.

Mutable means you can change an object after creating it. Immutable means Python prevents changes after creation.

Featurebytearraybytes
MutableYesNo
Stores values from 0 to 255YesYes
Supports indexing and slicingYesYes
Supports in-place updatesYesNo
Best forEditing binary dataFixed binary data
Common use casesBuffers, file updates, packet buildingHashes, API response content, fixed binary values

The following code shows the difference clearly:

employee_name = "Daniel Smith"

fixed_data = bytes(employee_name, "utf-8")
editable_data = bytearray(employee_name, "utf-8")

print("Before update:")
print(fixed_data)
print(editable_data)

editable_data[0] = ord("d")

print("\nAfter updating bytearray:")
print(editable_data)

Output:

Before update:
b'Daniel Smith'
bytearray(b'Daniel Smith')

After updating bytearray:
bytearray(b'daniel Smith')

I executed the above example code and added the screenshot below.

bytearray() Function Python

The ord() function returns the numeric Unicode value for one character. In this example, ord("d") returns 100, which Python stores as the first byte.

If you try to update fixed_data[0], Python raises a TypeError because a bytes object cannot change.

employee_name = "Daniel Smith"

fixed_data = bytes(employee_name, "utf-8")

fixed_data[0] = ord("d")

Output:

TypeError: 'bytes' object does not support item assignment

Create a Python bytearray() Object

You can create a bytearray in several ways. The right choice depends on the type of data your script already has.

Create bytearray from a string

Use a string and an encoding when you need editable binary text.

message = "Order received from Michael Brown"

message_buffer = bytearray(message, "utf-8")

print(message_buffer)
print(message_buffer.decode("utf-8"))

Output:

bytearray(b'Order received from Michael Brown')
Order received from Michael Brown

I executed the above example code and added the screenshot below.

bytearray() Function in Python

The decode() method converts the byte data back into a normal Python string. In most business scripts, UTF-8 is the safest default encoding because it supports English text and many other languages.

You can also learn more about converting bytes to strings in Python.

Create bytearray from a list of integers

Use a list when you already have numeric byte values. Every number must fall between 0 and 255.

color_values = [255, 128, 64, 0]

color_buffer = bytearray(color_values)

print(color_buffer)
print(list(color_buffer))

Output:

bytearray(b'\xff\x80@\x00')
[255, 128, 64, 0]

The first output displays some bytes with escape sequences. The second output converts the bytearray to a list, making the actual numeric values easier to read.

This pattern is useful when working with RGB color values, binary sensors, custom file formats, or low-level device data.

Create a bytearray with a fixed size

Pass an integer to create a bytearray full of zero values.

buffer_size = 8

data_buffer = bytearray(buffer_size)

print(data_buffer)
print(list(data_buffer))

Output:

bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
[0, 0, 0, 0, 0, 0, 0, 0]

This is useful when you know the size of a binary message before filling it. For example, a local automation script may reserve a fixed buffer for an eight-byte record ID.

Create bytearray from bytes

You can convert an existing bytes object into an editable bytearray.

api_response = b"STATUS:OK"

editable_response = bytearray(api_response)

editable_response[7:] = b"FAILED"

print("Original bytes:", api_response)
print("Updated bytearray:", editable_response)

Output:

Original bytes: b'STATUS:OK'
Updated bytearray: bytearray(b'STATUS:FAILED')

The original bytes value stays unchanged. The new bytearray gives you a separate editable copy.

Modify Data with Python bytearray()

The main reason to use bytearray() is simple: you can change its contents directly. This saves effort when a script builds or updates binary content in stages.

Change one byte by index

A bytearray uses zero-based indexing, just like Python lists and strings. The first position has index 0.

status_code = bytearray(b"FAIL")

print("Before:", status_code)

status_code[0] = ord("P")
status_code[1] = ord("A")
status_code[2] = ord("S")
status_code[3] = ord("S")

print("After:", status_code)
print("Decoded value:", status_code.decode("utf-8"))

Output:

Before: bytearray(b'FAIL')
After: bytearray(b'PASS')
Decoded value: PASS

Each position needs an integer from 0 through 255. Use ord() when you want to store a single text character.

Replace a range of bytes with slicing

Slicing lets you select several positions at once. You can replace a slice with bytes, a bytearray, or an iterable of valid integer byte values.

report_status = bytearray(b"Report: Pending")

report_status[8:] = b"Complete"

print(report_status)
print(report_status.decode("utf-8"))

Output:

bytearray(b'Report: Complete')
Report: Complete

The slice report_status[8:] starts at index 8 and continues to the end. Python replaces the word Pending with Complete.

This is a clean technique when an automation script creates a standard record format and updates one section before writing a file.

Append and extend bytearray data

Use append() to add one byte. Use extend() to add multiple bytes.

log_buffer = bytearray(b"Job started")

log_buffer.append(10)
log_buffer.extend(b"Job finished")

print(log_buffer)
print(log_buffer.decode("utf-8"))

Output:

bytearray(b'Job started\nJob finished')
Job started
Job finished

The number 10 represents a newline character (\n) in UTF-8 and ASCII text. append() accepts only one integer byte value, while extend() accepts several values.

To work more confidently with lists and sequences, review how to add elements to an empty list in Python.

Insert and remove bytes

A bytearray supports several list-like methods, including insert(), remove(), and pop().

packet = bytearray([10, 20, 40])

packet.insert(2, 30)
removed_value = packet.pop()

print("Updated packet:", list(packet))
print("Removed value:", removed_value)

Output:

Updated packet: [10, 20, 30]
Removed value: 40

This example builds a small numeric packet. insert(2, 30) places 30 before the item at index 2. Then pop() removes and returns the last value.

Useful Python bytearray() Methods

Python gives bytearray many familiar sequence methods. These methods help when you need to search, clean, split, or reverse binary data.

MethodWhat it does
append(value)Adds one integer byte
extend(data)Adds multiple bytes
insert(index, value)Inserts one byte at a position
pop(index)Removes and returns a byte
remove(value)Removes the first matching byte
clear()Removes every byte
decode(encoding)Converts byte data to text
find(sub)Returns the starting index of matching bytes
replace(old, new)Returns a new modified bytearray
split(separator)Splits data into a list of bytearrays
reverse()Reverses the byte order in place

Here is a practical example using find(), replace(), and split() to process a simple server log message.

log_entry = bytearray(b"USER=Emily Davis;ROLE=viewer;STATUS=active")

status_position = log_entry.find(b"STATUS=")
updated_log = log_entry.replace(b"viewer", b"editor")
fields = updated_log.split(b";")

print("Status position:", status_position)
print("Updated log:", updated_log.decode("utf-8"))
print("Fields:", [field.decode("utf-8") for field in fields])

Output:

St