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:

Status position: 29
Updated log: USER=Emily Davis;ROLE=editor;STATUS=active
Fields: ['USER=Emily Davis', 'ROLE=editor', 'STATUS=active']

Notice that replace() returns a new bytearray; it does not update log_entry in place. Always assign its result when you want to keep the replacement.

Pro Tip: In production scripts, I decode binary data only at the edge of the workflow, such as when I display a log message or create a text report. I keep the value as a bytearray while I edit binary content because repeated encoding and decoding adds unnecessary work and makes bugs harder to trace.

Python bytearray() for Binary Files

A common real-world use for bytearray() is editing a local binary file. For example, you may need to update a marker inside a generated report, binary export, or custom data file.

Use binary file modes:

  • "rb" reads a file as bytes
  • "wb" writes bytes to a file
  • "ab" appends bytes to a file

The following example creates a simple binary audit file, changes one word, and saves the result.

file_name = "audit_record.bin"

original_data = b"Customer: Olivia Wilson | Status: Pending"

with open(file_name, "wb") as file:
file.write(original_data)

with open(file_name, "rb") as file:
file_data = bytearray(file.read())

file_data = file_data.replace(b"Pending", b"Approved")

with open(file_name, "wb") as file:
file.write(file_data)

with open(file_name, "rb") as file:
saved_data = file.read()

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

Output:

b'Customer: Olivia Wilson | Status: Approved'
Customer: Olivia Wilson | Status: Approved

The with open(...) pattern closes the file automatically, even if your code raises an error. That prevents file-locking issues and makes local automation scripts more reliable.

For more file-writing patterns, read how to write bytes to a file in Python and how to open a file in Python.

Build a Simple Editable Record Buffer

Let’s use bytearray() in a complete mini-project. Imagine you receive a fixed-width customer record from an older system. The record stores:

  • Customer ID: 6 bytes
  • Status: 8 bytes
  • Region: 5 bytes

The script updates the status and prints the final record.

def format_field(value, size):
return value.ljust(size)[:size].encode("utf-8")


customer_id = "C10245"
status = "PENDING"
region = "TEXAS"

record = bytearray()
record.extend(format_field(customer_id, 6))
record.extend(format_field(status, 8))
record.extend(format_field(region, 5))

print("Original record:", record.decode("utf-8"))

new_status = format_field("ACTIVE", 8)
record[6:14] = new_status

print("Updated record:", record.decode("utf-8"))
print("Raw bytes:", record)

Output:

Original record: C10245PENDING TEXAS
Updated record: C10245ACTIVE TEXAS
Raw bytes: bytearray(b'C10245ACTIVE TEXAS')

The format_field() function makes every field the required length. It uses ljust() to add spaces on the right, then uses slicing to trim longer values. Finally, it encodes the text to bytes.

The slice record[6:14] points exactly to the eight-byte status field. This approach works well with legacy file exports, fixed-format integrations, and binary message builders.

If you want to strengthen your understanding of reusable logic, see how to define a function in Python and how to use Python functions with optional arguments.

Convert Between bytearray and Other Types

In a real Python project, data often moves between strings, byte arrays, lists, and immutable bytes.

Convert bytearray to bytes

Use bytes() when you finish editing and need an immutable value.

editable_message = bytearray(b"Invoice ready")

editable_message[8:] = b"sent"

final_message = bytes(editable_message)

print(final_message)
print(type(final_message))

Output:

b'Invoice sent'
<class 'bytes'>

This is useful when a library expects bytes, such as a hashing function or a network client that sends a completed request body.

Convert bytearray to a list

Use list() when you want to inspect individual numeric values.

signature = bytearray(b"OK")

numeric_values = list(signature)

print(numeric_values)

Output:

[79, 75]

The uppercase letter O has the byte value 79, and K has the byte value 75.

Convert a list to bytearray

Use bytearray() directly with a list of valid byte values.

temperature_data = [72, 73, 74, 75]

temperature_buffer = bytearray(temperature_data)

print(temperature_buffer)
print(list(temperature_buffer))

Output:

bytearray(b'HIJK')
[72, 73, 74, 75]

The first output looks like text because 72 through 75 match the ASCII values for H, I, J, and K. The values remain numeric bytes.

Things to Keep in Mind

  • Use values from 0 to 255: bytearray accepts only valid byte values. Passing -1 or 256 raises a ValueError.
  • Specify an encoding for strings: bytearray("Emma") raises an error because Python needs an encoding such as "utf-8" for text.
  • Remember that indexes return integers: data[0] returns a number, not a one-character byte string. Use data[0:1] if you need a one-byte slice.
  • Watch fixed-width slices: Replacing a slice with a longer value shifts later data. Pad or trim replacement values when you work with fixed-size records.
  • Use binary file modes: Open binary data with "rb" or "wb" to avoid unwanted text encoding conversions.
  • Avoid decoding arbitrary data: Random binary data may not use UTF-8. Decode only when you know the encoding or handle UnicodeDecodeError safely.

Frequently Asked Questions

What does bytearray() do in Python?

The Python bytearray() function creates a mutable sequence of byte values. You can use it to store and update binary data such as encoded text, file data, or packet content. Each item must hold a value from 0 through 255.

What is the difference between bytearray and bytes in Python?

A bytearray is mutable, so you can update, insert, and remove bytes after creation. A bytes object is immutable, so Python prevents direct changes. Use bytearray for editable binary buffers and bytes for fixed binary values.

How do I create a bytearray from a string in Python?

Pass the string and its encoding to bytearray(). For example, bytearray("Emma Johnson", "utf-8") converts the text into editable UTF-8 bytes. Use decode("utf-8") to convert it back to readable text.

Can I change a character in a bytearray?

Yes, but assign an integer byte value rather than a string. For example, data[0] = ord("A") replaces the first byte with the byte for A. You can also replace several characters by assigning bytes to a slice.

Why does bytearray return numbers when I use an index?

A bytearray stores numeric byte values, so indexing returns an integer from 0 through 255. For example, bytearray(b"AB")[0] returns 65. Use a slice such as data[0:1] if you need a one-byte bytearray result.

Can I write a bytearray to a file in Python?

Yes. Open the file in binary write mode with "wb" and pass the bytearray to file.write(). Python accepts both bytes and bytearray values in binary file operations.

The Python bytearray() function gives you a straightforward way to create and edit binary data, from small text buffers to fixed-width records and binary files. Start with strings and short byte sequences, then use indexing and slicing when your script needs controlled in-place updates. I hope you found this practical guide helpful.

You May Also Like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.