Python Glossary Русский

all Python 3Data typesterm

bytearray

bytes

A mutable sequence of bytes. Unlike bytes, it supports item assignment and the append() and extend() methods.

Syntax

bytearray(n)  bytearray(iterable)  bytearray(b"...")  bytearray(source, encoding)

Reach for bytearray when binary data is built up or patched piece by piece: append(), extend() and index/slice assignment mutate it in place instead of copying at every step. The price of mutability is that bytearray is unhashable — it can't be a dict key or set member, where you need the immutable bytes instead.

Examples

ba = bytearray(5); print(ba)      # → bytearray(b'\x00\x00\x00\x00\x00')
ba = bytearray(b"hello")
ba[0] = 72; print(ba)             # → bytearray(b'Hello')
ba.append(33); print(bytes(ba))   # → b'Hello!'
print(bytearray.fromhex("4142"))  # → bytearray(b'AB')
ba2 = bytearray(b"abc")
ba2.extend(b"def"); print(ba2)   # → bytearray(b'abcdef')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy