bytearray.insert()
Places a byte BEFORE the given position, shifting the rest right. Like list.insert, an impossible index clamps silently rather than raising.
Demo
The byte goes BEFORE the given position, so inserting at 0 puts it first and inserting at the length puts it last. The clamping cases are the ones to note: an index of 99 on a three-byte buffer does not raise — it simply appends. A negative index counts from the end, so -1 inserts before the LAST byte rather than after it, which is a persistent off-by-one.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| index | int | yes | Position to insert BEFORE. Negative counts from the end. Out-of-range values clamp to 0 or to the length. |
| byte | int | yes | An integer from 0 to 255. A bytes object raises TypeError. |
Return value
None — Returns None — the buffer is mutated. The demo wraps the call so the resulting buffer is visible.
Common patterns
buf.insert(0, len(payload))
buf.insert(HEADER_END, flag_byte)
buf.append(byte) # clearer than insert(len(buf), byte)
Examples
Pitfalls
b = bytearray(b'abc') b.insert(999, 122) b
if 0 <= i <= len(b): b.insert(i, byte) else: raise IndexError(i)
b = bytearray(b'abc') b.insert(-1, 122) b
b.append(122)
buf.insert(0, b'z')
buf.insert(0, ord('z'))
for v in values: buf.insert(0, v)
for v in values: buf.append(v) buf.reverse()
When to use
- Prepending a framing or length byte
- Splicing a value into a known offset
- Small buffers where the shift cost is irrelevant
- Adding at the end → append says what you mean
- Repeated prepending on a large buffer → build reversed, or use a deque
- Adding several bytes → extend, or slice assignment
Notes
FAQ
Because insert is defined to clamp, matching list.insert. It is convenient when the index comes from arithmetic that might overshoot, and a nuisance when you wanted validation — so validate explicitly if a bad index is a bug.
if not 0 <= i <= len(buf): raise IndexError(i)