ZetCode

Python bytearray function

last modified November 29, 2026 Python 3.15

In this article we show how the bytearray builtin creates a mutable sequence of bytes, and how that sequence is changed in place.

A bytearray stores integers from 0 to 255 like bytes, but every element can be replaced and the length can grow or shrink. That makes it the right container for a buffer that is assembled or edited piece by piece, while bytes remains the right type for data that is finished and should not change.

The immutable counterpart, its literals, decoding, and its methods are described in Python bytes. Reading and writing binary data from files is shown in Python read file.

Creating a bytearray

The constructor accepts no argument, a length, an iterable of integers, a bytes-like object, or a string together with an encoding.

create_bytearray.py
empty = bytearray()
zeros = bytearray(4)
letters = bytearray([70, 97, 108, 99, 111, 110])
copied = bytearray(b'falcon')
text = bytearray('naïve', 'utf-8')
counted = bytearray(range(3))

print(empty)
print(zeros)
print(letters)
print(copied)
print(text)
print(counted)
print(len(text))

A length produces that many zero bytes, not an empty sequence. An iterable supplies the values one by one, and a bytes object is copied, so later changes to copied do not touch the original literal.

The string form requires an encoding because a bytearray holds bytes, not characters. The word naïve needs two bytes for the letter ï in UTF-8, so the result is six bytes long.

$ python create_bytearray.py
bytearray(b'')
bytearray(b'\x00\x00\x00\x00')
bytearray(b'Falcon')
bytearray(b'falcon')
bytearray(b'na\xc3\xafve')
bytearray(b'\x00\x01\x02')
6

Changing items and slices

Indexing returns an integer and assignment stores an integer. Slices accept any bytes-like object, and the replacement may have a different length than the slice it replaces.

item_slices.py
data = bytearray(b'falcon')

data[0] = ord('F')
print(data)

data[1:3] = b'AL'
print(data)

data[4:4] = b'!!'
print(data)

del data[4:]
print(data)

try:
    data[::2] = b'xyz'
except ValueError as e:
    print('ValueError:', e)

The first assignment changes one byte. The slice assignment replaces two bytes with two, and the empty slice at position four inserts the exclamation marks without removing anything.

Deleting a slice removes the tail. All of these operations work on the same object; no new bytearray is created, which is the main difference from bytes, where every change produces a new value.

A slice with a step is stricter: the replacement must have exactly as many bytes as the slice, because a different length would change the positions that the step selects.

$ python item_slices.py
bytearray(b'Falcon')
bytearray(b'FALcon')
bytearray(b'FALc!!on')
bytearray(b'FALc')
ValueError: attempt to assign bytes of size 3 to extended slice of size 2

Growing and shrinking with methods

The usual sequence methods are available, and each one changes the length of the bytearray in place.

grow_shrink.py
data = bytearray(b'falcon')

data.append(33)
print(data)

data.extend(b' flies')
print(data)

data.insert(0, ord('>'))
print(data)

last = data.pop()
print(last, data)

data.remove(ord('!'))
print(data)

try:
    data.remove(ord('?'))
except ValueError as e:
    print('ValueError:', e)

print(data.count(ord('l')))

append takes a single integer, while extend takes an iterable of integers or a bytes-like object. insert places one byte at an index, shifting the rest to the right.

pop returns the removed byte, and remove deletes the first occurrence of a value. Both raise ValueError or IndexError when the byte is not there, so a buffer that is drained by several code paths needs a check or a try block.

$ python grow_shrink.py
bytearray(b'falcon!')
bytearray(b'falcon! flies')
bytearray(b'>falcon! flies')
115 bytearray(b'>falcon! flie')
bytearray(b'>falcon flie')
ValueError: value not found in bytearray
2

Bytes, hex, and text

A bytearray converts to the other binary representations without losing data. The conversions copy the content, so the original stays independent.

convert.py
data = bytearray(b'Hello')

print(bytes(data))
print(data.hex())

restored = bytearray.fromhex('48 65 6c 6c 6f')
print(restored)

text = bytearray('ZetCode', 'utf-8')
print(text.decode('utf-8'))
print(bytes(text).decode('ascii'))
print(bytearray('ZetCode'.encode('utf-8')))

try:
    bytes([0xff]).decode('utf-8')
except UnicodeDecodeError as e:
    print('UnicodeDecodeError:', e)

bytes(data) freezes the buffer, and hex turns it into a string of two-digit pairs. fromhex accepts spaces between the pairs but rejects an odd number of digits.

Decoding turns bytes back into text with a named encoding. The encoding used to create the buffer and the one used to decode it must agree; otherwise the bytes are reinterpreted or the decoder raises UnicodeDecodeError, as the last statement shows for a byte that cannot start a UTF-8 sequence.

$ python convert.py
b'Hello'
48656c6c6f
bytearray(b'Hello')
ZetCode
ZetCode
bytearray(b'ZetCode')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

A writable buffer with memoryview

A bytearray exposes the buffer protocol, so a memoryview can read and write it without copying. Slicing a memoryview produces another view on the same bytes.

memoryview_buffer.py
data = bytearray(b'falcon')
view = memoryview(data)

print(view.readonly)
print(view[1:4].tobytes())

view[0] = ord('F')
print(data)

view[4:6] = b'ON'
print(data)
print(bytes(view))

frozen = memoryview(b'falcon')
print(frozen.readonly)

try:
    frozen[0] = 70
except TypeError as e:
    print('TypeError:', e)

The view is not read-only because its source is mutable, and the slice view[1:4] is a view too, not a copy. Assigning through the view changes data immediately, which is how a function can fill a buffer owned by its caller.

A memoryview of a bytes object reports True for readonly and refuses assignment. The same code therefore works with both types as long as it only reads.

$ python memoryview_buffer.py
False
b'alc'
bytearray(b'Falcon')
bytearray(b'FalcON')
b'FalcON'
True
TypeError: cannot modify read-only memory

Draining a buffer with take_bytes

Python 3.15 adds bytearray.take_bytes, which removes bytes from the front or the end of the array and returns them as an immutable bytes object.

take_bytes.py
buffer = bytearray(b'HEADpayloadTAIL')

print(buffer.take_bytes(4))
print(buffer)

print(buffer.take_bytes(-4))
print(buffer)
print(len(buffer))

buffer.extend(b'END')
print(buffer.take_bytes())
print(buffer)

try:
    bytearray(b'ab').take_bytes(5)
except IndexError as e:
    print('IndexError:', e)

A positive count takes from the front and a negative count takes from the end. Without an argument the method takes everything, which leaves an empty bytearray.

The method is meant for buffered readers: a parser can consume a header, hand the bytes to the rest of the program, and keep the remaining bytes in the same object. Asking for more bytes than the array holds raises IndexError.

$ python take_bytes.py
b'HEAD'
bytearray(b'payloadTAIL')
b'payload'
bytearray(b'TAIL')
4
b'TAILEND'
bytearray(b'')
IndexError: can't take 5 bytes outside size 2

Comparing bytearray with bytes

Equality compares content, not the type, so a bytearray and a bytes object with the same bytes are equal. Ordering compares the numeric values from left to right.

compare_choose.py
data = bytearray(b'falcon')
frozen = b'falcon'

print(data == frozen)
print(data == bytearray(b'falcon'))
print(data < b'falcon!')
print(b'falcon' < data)

words = [bytearray(b'heron'), b'falcon', bytearray(b'eagle')]
print(sorted(words, key=bytes))

mixed = {'data': frozen}
mixed[bytes(data)] = 'also bytes'
print(mixed)

try:
    {data: 'mutable'}
except TypeError as e:
    print('TypeError:', e)

The shorter sequence is smaller when one is a prefix of the other, so falcon comes before falcon!.

A bytearray cannot be a dictionary key or a set member because it is unhashable; its content could change and the hash would no longer match the bucket. Convert it with bytes() before using it as a key, as the mixed dictionary does.

Sorting works without any conversion, because ordering is defined for both types. The key=bytes call only makes the comparison explicit; the result still holds the original bytearray and bytes elements.

Choose bytes for constants, file contents, and anything sent over a network, and bytearray for a buffer that is built or edited in place. The two types convert cheaply in either direction.

$ python compare_choose.py
True
True
True
False
[bytearray(b'eagle'), b'falcon', bytearray(b'heron')]
{'data': b'falcon', b'falcon': 'also bytes'}
TypeError: cannot use 'bytearray' as a dict key (unhashable type: 'bytearray')

Source

Python bytearray objects

Python bytes objects

Python memoryview objects

In this article we have created bytearrays from lengths, iterables, bytes, and text, changed them by index and by slice, grown and drained them, and moved their content to bytes and back. For the immutable type and its decoding rules, see Python bytes; for the constructor forms of the immutable type, see Python bytes function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.