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
| Parameter | Description |
|---|---|
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
data = bytearray(b"hello")
data[0] = ord("H")
data.extend(b"!")
print(data)
print(bytes(data))
Output
bytearray(b'Hello!') b'Hello!'
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
bytes()· Create an immutable sequence of bytes: raw binary data such as file contents, network messages or encoded text.memoryview()· Create a view of an object's binary data (bytes, bytearray, arrays) that slices and edits it without copying.ord()· Return the Unicode code point (an integer) of a single character, such as ord('A') giving 65. The inverse of chr().- Python Data Types · tutorial