Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python bytearray() function

Reference for Python bytearray(): create a mutable sequence of bytes from a size, an iterable, a string with an encoding or a buffer, then edit it in place.

bytearray is the mutable counterpart of bytes: a sequence of integers from 0 to 255 that you can change in place. You can assign to single items and slices, append, extend, insert and delete, which makes it a good buffer for building or editing binary data piece by piece.

Calling bytearray() creates one from a size, an iterable of integers, a string plus an encoding, or any object supporting the buffer protocol.

Python
buf = bytearray(b"abc")
buf[0] = 65            # bytearray(b'Abc')

Try it

Python Creating and editing a bytearray

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python bytes vs bytearray, and building a buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
bytearray()
bytearray(source)
bytearray(source, encoding)
bytearray(source, encoding, errors)
Name Description
source An int (that many zero bytes), an iterable of integers 0-255, a str (needs encoding), or an object with a buffer such as bytes or memoryview.
encoding Required when source is a str, for example "utf-8".
errors How to handle unencodable characters: "strict" (default), "ignore", "replace", ...

Return value: a new bytearray.

Raises: TypeError if a string is given without an encoding; ValueError if an item is outside 0-255; OverflowError or ValueError for a negative size.

Usage notes

  • Items are integers. data[0] is an int (for example 104), not a one-byte string. A slice such as data[0:1] is a bytearray.
  • Methods. It has most bytes methods (find, split, replace, hex, decode, ...) plus the mutable list-like ones: append, extend, insert, pop, remove, reverse, clear, copy.
  • Copies vs views. bytes(data) makes an immutable copy. memoryview(data) gives a zero-copy view you can slice and write through; the bytearray cannot be resized while a view exists.
  • Not hashable. Because it is mutable, a bytearray cannot be a dictionary key or set member. Convert to bytes first.
  • Efficient appends. Repeated += on a bytearray is amortized fast; repeated + on bytes copies every time.
  • Text. Decode with .decode("utf-8"). A multi-byte character split across edits will fail to decode.
  • Binary files. file.readinto(buffer) fills a preallocated bytearray without allocating a new object each read.