Python Glossary Русский

all Python 3Byte sequencesfunction

bytearray.insert

bytearray — mutating

Insert a byte at an index in place.

Syntax

ba.insert(...)

The index behaves like list.insert: an oversized one is clamped to the end, a negative one counts from the end, and you never get an IndexError — the byte just lands somewhere you did not expect. Inserting anywhere but the end shifts the whole tail, so it costs O(n); doing that in a loop over a large buffer is slow, better to collect pieces and join them.

Examples

ba = bytearray(b'ac')
ba.insert(1, 98)
print(ba)   # → bytearray(b'abc')

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy