bytearray()
A mutable byte buffer — for when bytes is not enough and you need append() or slice assignment.
Demo
bytearray has the same THREE call shapes as bytes. The demo shows the constructed value in Python's bytearray(b'...') display form. In real code the difference from bytes is what you can DO with the result: bytearray supports append(), extend(), pop(), item assignment (buf[0] = 255), and slice assignment. bytes is read-only.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| source | int | iterable | str | no ("") | The initial data. int: number of zero bytes. Iterable of ints: those bytes. String: requires encoding. |
| encoding | str | no | When source is a string, the encoding to use. |
| errors | str | no ("strict") | Error handler when encoding a string. |
Return value
bytearray — A MUTABLE sequence of bytes (integers 0..255). Same three call shapes as bytes: `bytearray(int)` → n zero bytes; `bytearray(iterable_of_ints)` → those bytes; `bytearray(str, encoding)` → same as str.encode. Supports item assignment and mutation methods.
Common patterns
buffer = bytearray(4096) n = sock.recv_into(buffer)
out = bytearray() for chunk in chunks: out.extend(chunk)
buf = bytearray(data) for i in range(len(buf)): buf[i] ^= 0xff # XOR each byte
result = bytes(mutable_buf)
Examples
Pitfalls
bytearray(5)
bytearray([5]) # bytearray(b'\x05') bytearray(b"5") # bytearray(b'5')
buf = buf.append(65)
buf.append(65)
b[0] = b"H"
b[0] = 72 # ord("H")
{bytearray(b"a"): 1}
{bytes(bytearray(b"a")): 1}
When to use
- Pre-allocated buffers for socket / file I/O
- Building bytes incrementally with append / extend
- In-place byte manipulation (XOR, bit flips, byte-level transforms)
- Any use case where you would use a bytes object but need to mutate
- Read-only data → bytes is smaller and hashable
- Very short bytes constants → b"..." literal is clearer
- You want the result as bytes at the end → convert with bytes(buf)
- You need dict / set membership → not hashable, use bytes
Notes
FAQ
bytes is IMMUTABLE and hashable — usable as a dict key or set element. bytearray is MUTABLE — supports append, extend, item and slice assignment. Both share all reading operations; bytearray adds mutation.