Python 3 reference · Built-in Functions

Python bytearray() Function

Create a mutable sequence of bytes (integers 0–255). Like bytes, but you can change, append and remove bytes in place.

Python 3 Since 3.0

Syntax

bytearray(source=b"")
bytearray(source, encoding, errors="strict")

Parameters

ParameterDescription
source optional An int (size, filled with zeros), a str (needs encoding), bytes, an iterable of ints, or a buffer.
encoding optional Used to encode a str source, e.g. "utf-8".
errors optional How to handle encoding errors. Default: "strict"

Return value

A new bytearray.

Examples

Change bytes in placeTry it yourself
data = bytearray(b"hello")
data[0] = ord("H")
data.extend(b"!")
print(data)
print(bytes(data))

Output

bytearray(b'Hello!')
b'Hello!'
Different ways to create oneTry it yourself
print(bytearray(3))
print(bytearray([72, 105]))
print(bytearray("héllo", "utf-8"))

Output

bytearray(b'\x00\x00\x00')
bytearray(b'Hi')
bytearray(b'h\xc3\xa9llo')

bytes vs bytearray

bytes is immutable (like str); bytearray is mutable (like list). Build binary data in a bytearray, then convert it with bytes() when it should no longer change.

Version history

VersionChange
Python 3.0Added