Python bytearray() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in type

Definition

In Python, bytearray is the mutable version of bytes: a sequence of integers from 0 to 255 that you can change in place. It accepts the same arguments as bytes(): a size, an iterable of ints, a bytes-like object, or a string with an encoding.

Besides the read-only methods of bytes (such as decode(), hex(), and find()), it supports list-like changes: item and slice assignment, append(), extend(), insert(), del, and reverse(). That makes it a good buffer for building binary data.

bytearray is a built-in type (a class) that you call like a function: each call creates a new bytearray object. Like every built-in, it lives in the builtins module and is always available without an import.

Syntax

Create one, then edit it in place.

python
buf = bytearray(b"hello")
buf[0] = ord("H")
buf.extend(b"!")
CallWhat it does
bytearray(4)Four zero bytes you can overwrite.
bytearray(b"abc")A mutable copy of existing bytes.
buf.append(33)Adds one byte (the int 33).
buf[1:3] = b"XY"Replaces a slice; the length may change.

Item assignment takes an int: write buf[0] = ord("H") or buf[0] = 72, not buf[0] = "H".

Library declarations
python
bytearray(source=b"")
bytearray(source, encoding, errors="strict")
# class bytearray: a mutable built-in type

Parameters

ParameterDescription
sourceOptional. An int (size), iterable of ints 0-255, bytes-like object, or str (with encoding).
encodingRequired when source is a str.
errorsOptional. Encoding error handler, default "strict".

Return Value

Return ValueDescription
bytearrayA new mutable byte sequence.

Python Examples

Example 1 — Change Bytes in Place

Fix the first letter, append and extend, and convert to an immutable copy.

python
buf = bytearray(b"hello")
buf[0] = ord("H")
buf.append(ord("!"))
buf.extend(b" :)")

print(buf)
print(bytes(buf))
print(len(buf))

How It Works

  1. Assign an int. buf[0] = ord("H") replaces byte 104 (h) with 72 (H).
  2. Grow the buffer. append() adds one byte and extend() adds several.
  3. Different repr. A bytearray prints as bytearray(b'...'); bytes(buf) makes an immutable copy.
  4. Length. Five letters, the exclamation mark, a space, a colon, and a parenthesis make 9 bytes.

Example 2 — Build and Rearrange a Byte Buffer

Start with zero bytes, fill a slice, add, delete, and insert bytes, then print hex and reverse.

python
data = bytearray(4)
data[1:3] = b"AB"
print(data)

data += b"CD"
del data[0]
data.insert(0, 0x2A)
print(data)
print(data.hex())
data.reverse()
print(data)

How It Works

  1. Zero-filled start. bytearray(4) holds four \x00 bytes; assigning b"AB" to slice 1:3 fills the middle.
  2. In-place +=. data += b"CD" extends the same object instead of creating a new one.
  3. Delete and insert. del data[0] drops the first zero and insert(0, 0x2A) adds an asterisk (42) at the front.
  4. Inspect and reverse. hex() shows all six values, and reverse() flips their order in place.

Example 3 — bytearray vs bytes: Slices, Decoding, and Hashing

Copy immutable bytes into a bytearray, grow a slice, decode the result, and try to use it as a dict key.

python
frozen = b"abc"
mutable = bytearray(frozen)
mutable[1:2] = b"XYZ"

print(frozen, mutable)
print(mutable.decode("ascii").lower())
print(mutable == b"aXYZc")

try:
    {mutable: 1}
except TypeError:
    print("bytearray is unhashable; use bytes as a dict key")

How It Works

  1. Independent copy. bytearray(frozen) copies the data, so changing mutable leaves frozen as b'abc'.
  2. Slices can grow. Replacing one byte (index 1) with three bytes makes the buffer two bytes longer.
  3. Shared methods. decode() works just like on bytes, and the two types compare equal by content.
  4. Not hashable. Mutable objects cannot be dict keys, so the dict literal raises TypeError.

Frequently Asked Questions

When you need to modify binary data in place, such as building a packet or editing a file buffer. Use bytes for fixed data and dict keys.
Call bytes(buf). It returns an immutable copy.
Decode it: buf.decode("utf-8").
Each element is an int from 0 to 255. Assign ord("A") or 65 instead.
Usually yes. bytes + bytes creates a new object every time, while bytearray.extend() grows one buffer in place.

Next: bytes()

Create an immutable sequence of byte values.

bytes() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful