Home Python Built-in Functions bytearray() Python bytearray() Function 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.
buf = bytearray(b"hello")
buf[0] = ord("H")
buf.extend(b"!") Call What 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 bytearray(source=b"")
bytearray(source, encoding, errors="strict")
# class bytearray: a mutable built-in type Parameters Parameter Description source Optional. An int (size), iterable of ints 0-255, bytes-like object, or str (with encoding). encoding Required when source is a str. errors Optional. Encoding error handler, default "strict".
Return Value Return Value Description bytearray A new mutable byte sequence.
Python Examples 1. Edit in place 2. Build binary data 3. Versus bytes Example 1 — Change Bytes in Place Fix the first letter, append and extend, and convert to an immutable copy.
buf = bytearray(b"hello")
buf[0] = ord("H")
buf.append(ord("!"))
buf.extend(b" :)")
print(buf)
print(bytes(buf))
print(len(buf)) bytearray(b'Hello! :)')
b'Hello! :)'
9 How It Works Assign an int. buf[0] = ord("H") replaces byte 104 (h) with 72 (H).Grow the buffer. append() adds one byte and extend() adds several.Different repr. A bytearray prints as bytearray(b'...'); bytes(buf) makes an immutable copy.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.
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) bytearray(b'\x00AB\x00')
bytearray(b'*AB\x00CD')
2a4142004344
bytearray(b'DC\x00BA*') How It Works Zero-filled start. bytearray(4) holds four \x00 bytes; assigning b"AB" to slice 1:3 fills the middle.In-place +=. data += b"CD" extends the same object instead of creating a new one.Delete and insert. del data[0] drops the first zero and insert(0, 0x2A) adds an asterisk (42) at the front.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.
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") b'abc' bytearray(b'aXYZc')
axyzc
True
bytearray is unhashable; use bytes as a dict key How It Works Independent copy. bytearray(frozen) copies the data, so changing mutable leaves frozen as b'abc'.Slices can grow. Replacing one byte (index 1) with three bytes makes the buffer two bytes longer.Shared methods. decode() works just like on bytes, and the two types compare equal by content.Not hashable. Mutable objects cannot be dict keys, so the dict literal raises TypeError.Frequently Asked Questions When should I use bytearray instead of bytes? 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.
How do I convert a bytearray to bytes? Call bytes(buf). It returns an immutable copy.
How do I convert a bytearray to a string? Decode it: buf.decode("utf-8").
Why does buf[0] = "A" fail? Each element is an int from 0 to 255. Assign ord("A") or 65 instead.
Is bytearray faster than concatenating bytes? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion